/**
 * 全局变量
 */
var v = new Date().getTime();
var GL_SELECTED = {};
var GL_PARTNANE = ''; //用户所在地区
var product_list = {}; //产品列表
var product_group_list = {};//团购产品列表
var product_small_group_list = {}; //微团购
var product_special_list = {}; //抢购水果列表
var product_package_list = {}; //套装水果列表
var _new_user_product_id = ''; //新手用户专享水果id
var product_share_status = 0;   //0商场产品详情页，1分享的产品详情页


/**
 * 路由路径
 */
Path.map("#/home").to(function(){
    home.init();
});

Path.map("#/home/:class").to(function(){
    home.cur_product_class = this.params['class'];
    home.init();
});

Path.map("#/street").to(function() { //街
    street.init();
});

Path.map("#/go_league/:id").to(function(){//指定加盟商跳转
    common.loading();
    select_area.set_user_league('some',this.params['id'],'0');
});

Path.map("#/product_special").to(function(){ //特价抢购
    common.loading();
    common.user_login(product_special.show_v2);
});

Path.map("#/product_package").to(function(){ //礼盒套装
    common.loading();
    //product_package.show();
    common.user_login(home.product_list_in_package);
});

Path.map("#/package_view/:type/:id").to(function(){ //礼盒套装详情
    common.loading();
    //console.log(this.params['type']);
    product_package.view(this.params['id'],this.params['type']);
});


Path.map("#/product_view/:type/:id").to(function(){ //产品详情
    product_share_status = 0;
    common.loading();
    home.show_product_info(this.params['id'],this.params['type']);

});

Path.map("#/product_share/:type/:pid").to(function(){ //分享产品详情
    product_share_status = 1;
    common.loading();
    var params = this.params['pid']+","+this.params['type'];
    common.user_login(home.show_share_product,params);
});

Path.map("#/cart/:type").to(function(){ //购物车
    common.loading();
    cart_bag.init_data();
    cart.data.voucher_fee = 0;
    config.cartType = this.params['type'];
    cart.data.cart_type = this.params['type'];
    cart.data.AddrVo.fee_free = city_fee.fee_free;
    cart.data.AddrVo.fee = city_fee.fee;
    cart.data.league_type = user.userBase.league_type;

    switch (this.params['type']) {
        case 2: //团购
            cart.count_group();
            break;
        default : //常规
            cart.count();
            //添加称重产品
            if(product_weighing.productData.length > 0){
                cart.data.weights = product_weighing.productData;
            }

            //按钮点击统计
            common.buttonClikcStatistics("index","index_car","去结算");
            break;
    }
    common.renderTpl("#app_content",'cart',cart.data);

    cart.get_info();
    ios_scroll_resert();
    get_sendTime(0,"normal");
    $('#buy_cart_div').css('min-height',($(window).height())+"px" );
});

Path.map("#/sure_play/:id/:orderno").to(function(){ //余额支付
    common.loading();
    var params = this.params['id']+","+this.params['orderno'];
    common.user_login(recharge.surePayOrder,params);
});

Path.map("#/aliPay/:id/:orderno").to(function(){ //支宝支付
    common.loading();
    var params = this.params['id']+","+this.params['orderno'];
    common.user_login(cart.aliPay,params);
});



Path.map("#/order").to(function(){ //我的订单
    common.loading();
    common.user_login(order_list.showOrderList,'noreceive');
});

Path.map("#/order/:status").to(function(){
    common.loading();
    var params = this.params['status'];
    common.user_login(order_list.showOrderList,params);
});

Path.map("#/group_buy/:pid/:title/:price").to(function(){ //团购购买
    // console.log(this.params.pid,this.params.title,this.params.price);
    cart_group.cart(this.params.pid,'团购递减',this.params.price);
});

Path.map("#/selectarea").to(function(){
    common.loading();
    select_area.getLeagueList();
});

Path.map("#/selectcity").to(function(){
    common.loading();
    select_area.get_city(undefined,undefined);
});

Path.map("#/send_ziti/:leagueId/:cityCode/:branchId/:cityName/:areaName/:type/:show_sort").to(function(){
    var params = {'leagueId':this.params.leagueId,'cityCode':this.params.cityCode,'branchId':this.params.branchId,'cityName':decodeURI(this.params.cityName),'areaName':decodeURI(this.params.areaName),'type':this.params.type,'show_sort':this.params.show_sort};
    //show_sort优先显示自提还是配送，type:进入自提还是配送选项卡
    select_area.send_ziti(params);
});

Path.map("#/selectcity/:city_name/:clallback").to(function(){
    common.loading();
    //select_area.city_code = '';
    //select_area.city_name = decodeURI(this.params.city_name);
    var params = decodeURI(this.params.city_name);
    common.need_callback=decodeURI(this.params.clallback);
    common.user_login(select_area.show_city_part,params);
});

Path.map("#/selectcity/:city_name").to(function(){
    common.loading();
    //select_area.city_code = '';
    //select_area.city_name = decodeURI(this.params.city_name);
    common.need_callback=1;
    var params = decodeURI(this.params.city_name);
    common.user_login(select_area.show_city_part,params);
});

Path.map("#/select_league/:league_id").to(function(){
    common.loading();
    select_area.city_code = '';
    select_area.league_id = decodeURI(this.params.league_id);
    function list_all_league(){
        select_area.get_city(0,0);
    }
    common.user_login(list_all_league);
});

Path.map("#/city/:code").to(function(){ //城市所有的分点
    common.loading();
    var params = this.params['code'];
    common.user_login(select_area.city_info,params);
});

Path.map("#/current_position").to(function(){ //所在地区信息
    common.loading();
    common.user_login(select_area.current_position);
});


Path.map("#/voucher").to(function(){ //我的优惠券
    common.loading();
    common.user_login(voucher.showUserVoucher);

});

Path.map("#/shareset/:orderid/:type").to(function(){ //设置分享订单
    //$("html,body").scrollTop(0);
    //shareOrder.shareSetInfo(this.params['orderid'],this.params['type']);
    var params = this.params['orderid']+","+this.params['type'];
    common.user_login(shareOrder.shareSetInfo,params);
});

Path.map("#/shareorder/:orderid/:user").to(function(){ //设置分享订单
    common.loading();
    shareOrder.userShareInfo(this.params['orderid'],this.params['user']);
});


Path.map("#/voucherview/:voucher_id").to(function(){ //优惠券详细信息
    common.loading();
    var params = this.params['voucher_id'];
    common.user_login(voucher.checkVoucher,params);
});

Path.map("#/vouchershare/:open_id/:voucher_id").to(function(){ //优惠券详细信息
    common.loading();
    common.no_juml_url = 1;
    var params = this.params['open_id']+","+this.params['voucher_id'];
    common.user_login(voucher.shareVoucher,params);
});

Path.map("#/exchange/:tabName").to(function(){ //我的积分
    common.loading();
    exchange.show_exchange(this.params['tabName']);
});

Path.map("#/prizeview/:prize_id").to(function(){ //兑换物品详情
   common.loading();
   exchange.show_prizeview(this.params['prize_id']);
   config.setPageMinHeight();
});

Path.map("#/prize/:prize_id").to(function(){ //兑换实物详情
   common.loading();
   exchange.show_prize(this.params['prize_id']);
   config.setPageMinHeight();
});

Path.map("#/course").to(function(){ //兑换实物详情
   common.loading();
   var course = {};
   var html = template('course', course);
   $("#app_content").html(html);
   tongji();
   render_user();
});

Path.map("#/privilege").to(function(){ //我的特权码
    common.loading();
    common.user_login(privilege.show_privilege);
    //privilege.show_privilege();
});

Path.map("#/privilege_enter/:mark_id").to(function(){ //我的特权码入口
    privilege.enter(this.params['mark_id']);
});

Path.map("#/privilegeinfo").to(function(){ //我的特权码
    common.loading();
    privilege.show_privilege_info();
});

Path.map("#/news/:news_id").to(function(){ //使用帮助
    common.loading();
    var params = this.params['news_id'];
    common.user_login(news.show_news,params);
});

Path.map("#/aftersale/:uid/:oid").to(function(){ //售后服务入口
    common.loading();
    var params = this.params['uid']+","+this.params['oid'];
    common.user_login(aftersale.entrance, params);
});

Path.map("#/appraise/:orderno").to(function(){ //售后评价快递员
    common.loading();
    var params = this.params['orderno'];
    common.user_login(aftersale.get_appraise_info,params);
});

Path.map("#/scan_code/:id").to(function() { //售后用户描码
    common.loading();
    scan_code.oauthLogin(this.params['id']);
});

Path.map("#/scan_course").to(function() { //售后用户描码
    common.loading();
    scan_code.scanCourse();
});

Path.map("#/bingo_code").to(function() { //售后用户描码
    common.loading();
    scan_code.bingoCode();
});

Path.map("#/thank/:orderno/:status").to(function(){ //评价成功
    common.loading();
    var params = this.params['orderno']+","+this.params['status'];
    common.user_login(aftersale.aftersale_thank,params);
});

Path.map("#/return_goods/:oid/:pid/:price/:weights").to(function(){ //售后退换水果
    common.loading();
    var params = this.params['oid']+","+this.params['pid']+","+this.params['price']+","+this.params['weights'];
    common.user_login(aftersale.return_goods,params);
});

Path.map("#/feedback/:oid/:pid/:weight").to(function(){ //售后退货进度跟踪
    common.loading();
    var params = this.params['oid']+","+this.params['pid']+","+this.params['weight'];
    common.user_login(aftersale.feedback,params);
});



Path.map("#/aftersale_red").to(function(){ //领取群红包
    common.loading();
    aftersale.get_red();
});

Path.map("#/courier_complaint/:oid").to(function(){ //售后投诉快递员
    common.loading();
    common.user_login(aftersale.courier_complaint,this.params['oid']);
    // aftersale.courier_complaint(this.params['oid']);
});

Path.map("#/complaint_success").to(function(){ //售后投诉快递员成功
    common.loading();
    aftersale.complaint_success();
});


Path.map("#/return_exchange/:orderno/:type").to(function(){ //退货换货
    common.loading();
    aftersale.return_exchange(this.params['orderno'],this.params['type']);
});

Path.map("#/complete/:user_id/:order_id").to(function(){ //完成页面
   // common.loading();
    var params = "'"+this.params['user_id']+"','"+this.params['order_id']+"',''";
    common.user_login(cart.complete,params);
});

Path.map("#/complete/:user_id/:order_id/:order_type").to(function(){ //完成页面
   // common.loading();
    var params = "'"+this.params['user_id']+"','"+this.params['order_id']+"','"+this.params['order_type']+"'";
    common.user_login(cart.complete,params);
});

Path.map("#/blacklist").to(function(){ //黑名单
    common.blacklist();
});

Path.map("#/tracking/:orderon/:model").to(function(){ //订单跟踪
    common.loading();
    if(this.params['model'] == 'normal') {
        common.user_login(tracking.getNormalModel,this.params['orderon']);
    }
    if(this.params['model'] == 'map') {
        common.user_login(tracking.getMapModel,this.params['orderon']);
    }
});

Path.map("#/group/:id/:lineup/:uid/:type/:part").to(function(){ //url触发团购
    if( _user_has_league != 1) {
        _user_come_from ='#/group/'+this.params['id']+'/'+this.params['lineup']+'/'+this.params['uid']+"/"+this.params['type']+'/'+decodeURI(this.params['part']);
        window.location.href = '#/selectarea';
        return false;
    }
    cart_group.order_come_from = 1;
    user.userBase.id = this.params['uid'];
    user.userBase.user_type = this.params['type'];
    cart_group.line = this.params['lineup'];
    user.userBase.short_name = decodeURI(this.params['part']);
    cart_group.urlGroup(0,this.params['id']);
});

Path.map("#/group/:id/:lineup").to(function(){ //团购排队订单
    cart_group.order_come_from = 1;
    cart_group.line = this.params['lineup'];
    cart_group.urlGroup(0,this.params['id']);
});

Path.map("#/recharge").to(function(){ //我的充值
    common.loading();
    common.user_login(recharge.user_recharge);
});

Path.map("#/recharge_ice").to(function(){ //我的充值
    common.loading();
    common.user_login(recharge.recharge_ice);
});


Path.map("#/map_address").to(function(){
    common.loading();
    common.user_login(map_address.create_map);
});

Path.map("#/bingo_voucher").to(function(){
    common.loading();
    common.user_login(bingo.voucher);
});

Path.map("#/bingo_meet").to(function(){
    common.loading();
    common.user_login(bingo.meet);
});

Path.map("#/bingo_meet_menu").to(function(){
    common.loading();
    common.user_login(bingo.meetMenu);
});

Path.map("#/bingo_prize").to(function(){
    common.loading();
    common.user_login(bingo.prize);
});

Path.map("#/bingo_invite").to(function(){
    common.loading();
    common.user_login(bingo.invite);
});

Path.map("#/bingo_invite_rule").to(function(){
    common.loading();
    common.user_login(bingo.invite_rule);
});

Path.map("#/thrifty").to(function(){       //省钱快报
    common.loading();
    common.user_login(thrifty.show);
});

Path.map("#/notice_list").to(function(){ //消息列表
    common.loading();
    common.user_login(notice.list);
});

Path.map("#/broadcast_room").to(function(){ //直播间
    common.loading();
    common.user_login(broadcast.init);
});


Path.map("#/notice_post/:id").to(function(){ //消息文章内容
    common.loading();
    common.user_login(notice.post,this.params['id']);
});

/* 订悦产品列表 */
Path.map("#/booking").to(function(){
    common.loading();
    navigation.menuType = 0;
    common.user_login(booking.entrance);
});
Path.map("#/booking/:type").to(function(){
    common.loading();
    var params = this.params['type'];
    common.user_login(booking.entrance,params);
});

/* 订悦购物车 */
Path.map("#/booking_cart").to(function(){
    // common.loading();
    booking.cart();
});

/* 订悦订单下单成功 */
Path.map("#/booking_success/:order_id").to(function(){ //完成页面
   // common.loading();
    var params = this.params['order_id'];
    common.user_login(booking.submitSuccess,params);
});

/* 订悦详情页 */
Path.map("#/booking_view").to(function(){
    common.loading();
    common.user_login(booking.view);
});

/* 订悦订单列表页 */
Path.map("#/booking_order").to(function(){
    common.loading();
    common.user_login(booking.order);
});

/* 订悦特定的订单列表页 */
Path.map("#/booking_order/:status").to(function(){
    common.loading();
    var params = this.params['status'];
    common.user_login(booking.order,params);
});

/* 订悦我要退订 */
Path.map("#/booking_unsubscribe/:orderid").to(function(){
    common.loading();
    var params = this.params['orderid'];
    common.user_login(booking.unsubscribe,params);
});

/* VIP */
Path.map("#/vip/:type").to(function(){
    if(this.params['type'] == 1){
        user.islogin = 0;
    }
    common.loading();
    var params = this.params['type'];
    common.user_login(vip.entrance,params);
});

/* 成为VIP */
Path.map("#/getVip").to(function(){
    common.loading();
    common.user_login(vip.getVip);
});

Path.map("#/email").to(function(){
    common.loading();
    common.user_login(config.email);
});

Path.root("#/home");
$(document).ready(function(){
    Path.listen();
});



Number.prototype.toFixed = function(num) {
    //重新构造toFixed方法,IE5.0+
    with(Math)this.NO=round(this.valueOf()*pow(10,num))/pow(10,num);
    return String(/\./g.exec(this.NO)?this.NO:this.NO+"."+String(Math.pow(10,num)).substr(1,num));
}

function minHeight() { //设置最低高度
     $('#view_page').css('min-height',($(window).height() - 50)+"px" );
     share_info = home_share_info;
}

//渲染用户抽屉界面
function render_user(){
    var url=api_host+"/Api/Users/oauth_login";
    var openid=user.userBase.bingo_openid;
    if (openid==undefined || openid==null || openid.length==0){
        return false;
    }
    var data={
        bingo_secret:'fb92390dd7c59c3fcb4fcce4801aadecb79f2e4a'
        ,bingo_appid:config.appid
        ,oauth_type:4
        ,oauth_openid:openid
    };
    if (user.islogin==0){
        $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
            if(result.status == "-01009") { //黑名单
                _bingo_blacklist_user = 1;
                if(_bingo_blacklist_user == 1) {
                    window.location.href = '#/blacklist';
                }
                return false;
            }
            if (result.status==1){
                user.islogin = 1;
                user.userBase=result.data;
                user.userBase.bingo_openid=openid;
                if(user.userBase.league_id == '' || user.userBase.league_id==0 ) {
                    select_area.get_user_auto_league();
                    //window.location.href = '#/selectarea';
                    window.location.href="./location.php?league_id=0&city_code=0&open_id="+openid+"&slatitude="+result.data.slatitude+"&slongitude="+result.data.slongitude;
                }
                if(user.userBase.user_type != 1) {
                    $('#user-no-focus').show();
                    if (browser.versions.iPhone || browser.versions.iPad || browser.versions.ios) {
                        $('#user-no-focus-height').css('height',$('#user-no-focus').height()+'px');
                    } else {
                        $('#view_page').css('paddingTop',$('#user-no-focus').height()+'px');
                    }
                }
                render_account();
            }else{
                //alert("登录异常，请重新进入商城");
                window.location.reload();
            }
        }});
    }else{
        render_account();
    }


}
//执行渲染抽屉
function render_account(){
    var short_name = user.userBase.short_name != '' ? user.userBase.short_name : '总部';
    if(GL_PARTNANE == '') {
       GL_PARTNANE =  short_name;
       $("#area_short_name").text(GL_PARTNANE);
    }
    var user_html=template('account', user);
    $("#userBase").html(user_html);
}

var actives = {}
actives.cart = [];
actives.subProduct = [];
actives.user_join_box = 0;
actives.add_price_status = 1;
actives.add_price_cancel = {}; //用户主动取消的商品
actives.join_data = {}; //用户参加活动

/**
 * 活动初始化
 * @method actives.init
 * @param {Object} object 对象
 */
actives.init = function(object) {
    var data = object || '';
    if(data == '') {
        actives.activeControlBox(actives.user_join_box);
        return false;
    }

    actives.join_data = {
        'BuyNGetOne':'',
        'man_x_jian_y':'',
        'discount_activity':'',
        'man_x_give_voucher':'',
        'N_bei_points': '',
        'add_price':''
    };

    actives.user_join_box = (actives.user_join_box == 1) ? 1 : 0;
    actives.fullFeeControl(data.BuyNGetOne); //买N免1
    actives.manjianControl(data.man_x_jian_y);//满X减Y
    actives.discountControl(data.discount_activity);//打折活动
    actives.mansongControl(data.man_x_give_voucher);//满x送代金券
    actives.nPointsControl(data.N_bei_points);//N倍积分
    actives.subProductsControl(data.sub_products); //子产品
    actives.activeControlBox(actives.user_join_box);

    if (actives.add_price_status == 1) {
        cart.show_add_price(); //加价购
    }

}

/**
 * 获得参加活动id字符串
 * @method actives.getJoinList
 */
actives.getJoinList = function() {
    var ids = '',num = 0;;
    if(cart.add_product_cart.selected >= 1) { //加价购
        actives.join_data['add_price'] = cart.data.add_price['event_id'];
    }

    for(var i in actives.join_data) {
        if(actives.join_data[i] != '' && actives.join_data[i] != undefined && actives.join_data[i] != null) {
            num++
            ids += actives.join_data[i] + ','
        }
    }

    if(num > 0) {
        return ids.substring(0,ids.length - 1);
    } else {
        return '';
    }
}

/**
 * 活动项目控制显示
 * @method actives.activeControlBox
 * @param {Number}  status 状态
 */
actives.activeControlBox = function(status) {
    if(status == 1) {
        $('.user-join-actives').show();
        $('.shopping-bag-select-btn').addClass('shopping-bag-select-activeing');
    } else {
        $('.user-join-actives').hide();
        $('.shopping-bag-select-btn').removeClass('shopping-bag-select-activeing');
    }
}

/**
 * 满x减y控制
 * @method actives.manjianControl
 * @param {Object} object 对象
 */
actives.manjianControl = function(object) {
    var data = object || {};
    if(common.isOwnEmpty(data)) {
        $('#man_x_jian_y').hide();
        return false;
    }

    var result = actives.manjianOpera(object.min_order_fee,object.get_free_fee,object.appoint_pid,object.appoint_title,object.vip_stauts);
    actives.user_join_box = 1;
    $('#man_x_jian_y').css('display','block');
    $('#man_x_jian_y').html(data.event_name);
    $('#man_x_jian_y').data('info',result.remark);
    $('#man_x_jian_y').data('save',result.save);
    if(parseInt(result.save) == 0) {
        actives.join_data['man_x_jian_y'] = '';
        $('#man_x_jian_y').removeClass('man_x_jian_y-join-current');
    } else {
        actives.join_data['man_x_jian_y'] = data.event_id;
        $('#man_x_jian_y').addClass('man_x_jian_y-join-current');
    }
}

/**
 * 满x减y,减免可以叠加，指定产品减满,仅限正常水果价钱
 * @method actives.manjianOpera
 * @param {Number} min_fee 最低金额
 * @param {Number} free_fee 免费金额
 * @param {String} ids 指定产品字符串
 * @param {String} titles 指定产品名称
 * @param {Number} vip 用户是否vip
 * @return {Object}
 */
actives.manjianOpera = function(min_fee, free_fee, ids, titles, vip) {
    var prefix = '';
    var total_fee = 0;
    var lists = ids || 0;
    var titles = titles || '';
    var data = { save: 0, remark:''};
    var min_fee = parseFloat(min_fee);
    var free_fee = parseFloat(free_fee);

    if(vip == 1 && !common.isVip()) {
        data.remark = $('#man_x_jian_y').html() + ',仅限会员哦';
        return data;
    }

    if(lists == 0) {
        total_fee = actives.normalGoodsTotal();
    } else {
        var result = actives.appointGoodsTotal(ids);
        prefix = "购买"+titles+"任意一款或多款产品";
        total_fee  = result.total_fee;
    }

    if(total_fee >= min_fee) {
        data.save = free_fee * Math.floor(total_fee / min_fee);
        data.remark = prefix+"满"+min_fee+"减"+free_fee+"活动，已减免"+data.save+"元";
    } else {
        var remain = min_fee - total_fee;
        data.remark = prefix+"满"+min_fee+"减"+free_fee+"活动正在进行，还差"+base.setNumberIntegral(remain)+"元就可以参与哦";
    }

    return data;
}

/**
 * 满x送代金券控制
 * @method actives.mansongControl
 * @param {Object} object 对象
 */
actives.mansongControl = function (object) {
    var data = object || {};
    if(common.isOwnEmpty(data)) {
        $('#man_x_give_voucher').hide();
        return false;
    }
    var result = actives.mansongOpera(object.min_order_fee,object.voucher_name,object.nums,object.fruit_id,object.vip_stauts);
    actives.user_join_box = 1;
    $('#man_x_give_voucher').css('display','block');
    $('#man_x_give_voucher').html(data.event_name);
    $('#man_x_give_voucher').data('info',result.remark);
    if(parseInt(result.is_give) == 0) {
        actives.join_data['man_x_give_voucher'] = '';
        $('#man_x_give_voucher').removeClass('man_x_give_voucher-current');
    } else {
        actives.join_data['man_x_give_voucher'] = data.event_id;
        $('#man_x_give_voucher').addClass('man_x_give_voucher-current');
    }
}

/**
 * 满x送代金券
 * @method actives.mansongOpera
 * @param {Number} min_fee 最低金额
 * @param {String} vname 优是券名称
 * @param {Number} vnum 优惠券多少张
 * @param {Number} id 指定产品id
 * @param {Number} vip 用户是否vip
 * @return {Object} Object
 */
actives.mansongOpera = function(min_fee, vname, vnum, id, vip)  {
    var id = id || 0;
    var total_fee = 0;
    var data = { is_give: 0, remark:''};
    var min_fee = parseFloat(min_fee);
    var prefix = '满'+min_fee+'元送'+vnum+'张'+vname;

    if(vip == 1 && !common.isVip()) {
        data.remark = $('#man_x_give_voucher').html() + ',仅限会员哦';
        return data;
    }

    if(id == 0) {
        total_fee = actives.normalGoodsTotal();
    } else {
        var result = actives.appointGoodsTotal(id);
        total_fee = result.total_fee;
        prefix = '买'+result.titles+prefix;
    }

    if(total_fee >= min_fee) {
        data.is_give = 1;
        data.remark = prefix;
    } else {
        var remain = min_fee - total_fee;
        data.remark = prefix+"活动正在进行，还差"+base.setNumberIntegral(remain)+"元就可以参与哦";
    }
    return data;
}

/**
 * 买x免y控制
 * @method actives.fullFeeControl
 * @param {Object} object 对象
 */
actives.fullFeeControl = function(object) {

    var data = object || {};
    if(common.isOwnEmpty(data)) {
        $('#man_x_give_voucher').hide();
        return false;
    }
    var result = actives.fullFeeOpera(object.min_product_count,object.vip_stauts);

    actives.user_join_box = 1;
    $('#BuyNGetOne').css('display','block');
    $('#BuyNGetOne').html(data.event_name);
    $('#BuyNGetOne').data('info',result.remark);
    $('#BuyNGetOne').data('save',result.save);
    $('#BuyNGetOne').data('vip',object.vip_stauts);

    if(parseFloat(result.save) > 0) {
        actives.join_data['BuyNGetOne'] = data.event_id;
        $('#BuyNGetOne').addClass('BuyNGetOne-join-current');
    } else {
        actives.join_data['BuyNGetOne'] = '';
        $('#BuyNGetOne').removeClass('BuyNGetOne-join-current');
    }
}

/**
 * 买x免y
 * @method actives.mansongOpera
 * @param {Number} min_product_count 最低购买数
 * @return {Object} Object
 */
actives.fullFeeOpera = function(min_product_count) {
    var buycar = getCookie('buycar') || '';
    buycar = product_weighing.buycartAddWeights(buycar);

    if(common.isNull(buycar)) {
        return false;
    }

    var goods = buycar.split("|");
    if(common.isOwnEmpty(goods)) {
        return false;
    }

    var sum = 0;
    var remark = "现有满"+min_product_count+"免1活动，满"+min_product_count+"份水果，最低一份免费(特价水果和礼盒套装均不参与)";
    var result = { save: 0, remark: remark };
    var data = new Array();
    var vip = $('#BuyNGetOne').data('vip');

    if(vip == 1 && !common.isVip()) {
        result.remark = $('#BuyNGetOne').html() + ',仅限会员哦';
        return result;
    }

    for(var i in goods) {
        var item = goods[i].split(',');
        var product = product_list[item[0]];
        if(!common.isOwnEmpty(product)) {
            if(actives.isWeights(product.id)) { //称重
                product.num = item[2]
                product.price = item[3];
            }

            for(var j = 0; j < product.num; j++ ) {
                var object = {};
                object.id = product.id;
                object.title = product.title;
                object.price = product.price;
                object.num = product.num;
                data.push(object);
                sum++;
            }
        }
    }

    var num = parseInt(sum / min_product_count);
    if(num > 0) {
        data.sort(function (x, y) { //数组以价格排序
            return x.price - y.price;
        });

        var save = 0;
        var fruitStr = '';
        var noRepectFruit = new Array();
        var feeFruit = data.slice(0, num);
        for (var k in feeFruit) { //计算省了多少钱
            save += parseFloat(feeFruit[k].price);
            noRepectFruit[feeFruit[k].title] = noRepectFruit[feeFruit[k].title] + 1 || 1;
        }

        if (save > 0) {
            for (var k in noRepectFruit) {
                fruitStr += k + '商品' + noRepectFruit[k] + '份,'
            }
        }
        result.save = base.setNumberIntegral(save);
        result.remark = "你已参与满"+min_product_count+"免1活动，系统已为您赠送了"+fruitStr+"免"+result.save+ "元(特价水果和礼盒套装均不参与本次买"+min_product_count+"免1活动)";
    }
    return result;
}

/**
 * 是否称重产品
 * @method actives.isWeights
 * @param {Number} id 商品id
 */
actives.isWeights = function(id) {
    var data = product_weighing.productData;

    for(var i in data) {
        if(data[i].id == id) {
            return true;
        }
    }
    return false;
}

/**
 * 打折控制器
 * @param  {Object} object
 * @returns {boolean}
 */
actives.discountControl = function(object) {
    var data = object || {};
    if(common.isOwnEmpty(data)) {
        $('#discount_activity').hide();
        return false;
    }

    var result = actives.discountOpera(data.discount_upper_limit, data.order_discount, data.pay_type, data.allow_goods_list, data.config_buy_count,data.contain_voucher, data.remark,data.vip_stauts);
    actives.user_join_box = 1;
    $('#discount_activity').css('display','block');
    $('#discount_activity').html(data.event_name);
    $('#discount_activity').data('info',result.remark);
    $('#discount_activity').data('save',result.save);
    $('#discount_activity').data('old_save',result.save);
    $('#discount_activity').data('pay',data.pay_type);
    $('#discount_activity').removeClass('discount_activity-join-current');

    var discount_activity_status = 0;
    var save = $('#discount_activity').data('old_save');
    var pay_type = $("input[name='pay_type']:checked").val();
    var pay_type_list = data.pay_type;

    pay_type_list = pay_type_list.split(',');
    if(save > 0) {
        for (var i in pay_type_list) {
            if (pay_type_list[i] == pay_type) {
                discount_activity_status = 1;
                cart.data.online_discount_pay = 1;
                $('#discount_activity').data('save', save);
                actives.join_data['discount_activity'] = data.event_id;
                $('#discount_activity').addClass('discount_activity-join-current');
            }
            if (discount_activity_status == 0) {
                cart.data.online_discount_pay = 0;
                $('#discount_activity').data('save', 0);
                actives.join_data['discount_activity'] = '';
                $('#discount_activity').removeClass('discount_activity-join-current');
            }
        }
    }

    /*
    if(data.show_status == 1 && data.order_discount != '' && data.order_discount != undefined) {
        for (var i in pay_type_list) {
            $('#pay_type' + pay_type_list[i]).parent().find('span.weixin_discout').html(data.order_discount + '折');
            $('#pay_type' + pay_type_list[i]).parent().find('span.weixin_discout').css('display', 'inherit');
        }
    }*/
}

/**
 * 打折活动
 * @method actives.discountOpera
 * @method {Number} upperFee 优惠金额上限
 * @param {Number} discount 几折
 * @param {String} pay_list 付款方式字符串
 * @param {String} ids 指定水果
 * @param {Number} buy_count 最底购买数
 * @param {Number} priority 优惠券之前
 * @param {String} markword 提示语
 * @param {Number} vip 优惠券
 */
actives.discountOpera = function(upperFee, discount, pay_list, ids, buy_count, priority, markword, vip) {
    var data = { save: 0, remark: ''};
    if(vip == 1 && !common.isVip()) {
        data.remark = $('#discount_activity').html() + ',仅限会员哦';
        return data;
    }

    var result = actives.discountPayType(pay_list);
    if(result.status == 0) {
        data.remark = result.data;
        return data;
    }

    var buycar = getCookie('buycar');
    buycar = product_weighing.buycartAddWeights(buycar);
    if(common.isNull(buycar)) {
        return false;
    }

    var goods = buycar.split("|");
    if(common.isOwnEmpty(goods)) {
        return false;
    }

    var save = 0;
    var remark = '';
    var total_fee = 0;
    var ids = ids || '';
    var buy_count = buy_count || 0;
    var discountRole = '';
    var priority = priority || 0;
    var markword = markword || '';

    if(ids == '') {
        total_fee = actives.normalGoodsTotal();
    } else {
        var result = actives.appointGoodsTotal(ids);
        total_fee = result.total_fee;
    }

    if(ids != '' && parseInt(buy_count) >= 1) {
        if(result.num < parseInt(buy_count)) {
            data.remark = '购买'+result.titles+'大于等于'+buy_count+'份才可以打'+discount+'折';
            return data;
        }
    }

    if(ids == '' && priority == 1 ) { //使用优惠券之前进行计算,指定产品无效
        var money = cart.data.voucher_fee;
        save = (total_fee - money) * (10 - parseFloat(discount)) / 10;
    } else {
        save = total_fee - total_fee * parseFloat(discount) / 10
    }

    save = base.setNumberIntegral(save);
    data.save = (save > upperFee) ? upperFee : save;
    remark = "您已参加"+discountRole+"用户"+discount+"折优惠活动，最高可减免"+upperFee+"元，现已优惠"+data.save+"元";
    data.remark = (markword != '') ? markword : remark;
    return data;
}


/**
 * 打折支持的方式
 * @param {String} pay_list 付款方式列表
 * @returns {{status: number, data: string}}
 */
actives.discountPayType = function(pay_list) {
    var pay_list = pay_list || '';
    var data = { status: 0, data: ''};
    var pay_type = $("input[name='pay_type']:checked").val();
    if(pay_list == '') {
        return data;
    }

    pay_list = pay_list.split(',');
    for(var i in pay_list) {
        if(pay_list[i] == pay_type) {
            data.status = 1;
        }
    }

    if(data.status == 0) {
        for(var i in pay_list) {
            var name;
            switch (parseInt(pay_list[i])) {
                case 0:
                    name = '货到付款';
                    break;
                case 1:
                    name = '微信支付';
                    break;
                    return
                case 2:
                    name = '货到付款';
                    break;
                case 3:
                    name = '货到付款';
                    break;
                default :
                    name = '指定支付方式';
                    break;
            }
            data.data += name+',';
        }
        data.data += '下单才可打折';
    }
    return data;
}

/**
 * N倍积分控制器
 * @method nPointsControl
 * @param {Object} object 对象
 */
actives.nPointsControl = function(object) {
    var data = object || {};
    if(common.isOwnEmpty(data)) {
        $('#N_bei_points').hide();
        return false;
    }

    actives.user_join_box = 1;
    $('#N_bei_points').css('display','block');
    $('#N_bei_points').html(data.event_name);
    $('#N_bei_points').data('info',data.remark);
    $('#N_bei_points').addClass('N_bei_points-current');
    actives.join_data['N_bei_points'] = data.event_id;

    if(object.vip_stauts == 1 && !common.isVip()) {
        $('#N_bei_points').data('info',$('#N_bei_points').html() + ',仅限会员哦');
        $('#N_bei_points').removeClass('N_bei_points-current');
        actives.join_data['N_bei_points'] = '';
    }
}

/**
 * 商品子产品控制器
 * @method actives.subProductsControl
 * @param {Object} object 对象
 */
actives.subProductsControl = function(object) {
    var data = object || ''
    if(data == '') {
        $('#sub_product_tips').hide();
        return false;
    }

    var result = actives.getCurrentSubProduct();
    actives.removeUserSelectedSubProduct();

    var data = [], remark = '', item = '', num = 0;
    for(var i in result) {
        num++;
        item = actives.subProduct[result[i]];
        data.push(item);
        remark += item['subtitle']+"<br/>";
    }

    common.renderTpl("#cart-sub-products","./cart/cart_sub_products",{data: data});

    var length = $('#cart-add-products').children().length;
    if(num == 0) {
        if(length == 0) {
            $('#cart-add-products-wrap').hide();
        }
        $('#sub_product_tips').data('info','没有可换购商品');
        $('#sub_product_tips').removeClass('sub_product-current');
        return false;
    }

    if(length > 0) {
        $('#cart-sub-products div:first-child').css('border-top', 'solid 1px #e8e8e8');
        $('#cart-sub-products div:first-child').css('margin-top', '10px');
    }

    actives.user_join_box = 1;
    $('#user-join-actives').show();
    $('#cart-add-products-wrap').show();
    $('#sub_product_tips').data('info',remark);
    $('#sub_product_tips').css('display','block');
    actives.userSubProduct(cart.sub_product_cart);
}

/**
 * 用户选择子商品
 * @method actives.selectSubProduct
 * @param {Number} id 商品id
 * @param {String} title 商品名称
 * @param {Number} prcie 商品价钱
 * @param {Number} kucan 商品库存
 */
actives.selectSubProduct = function(id, title, price) {
    if($('.add-price-selected-'+id).hasClass('current')) {
        $('.add-price-selected-'+id).removeClass('current');
        cart.sub_product_cart[id] = '';
        cart.sub_product_total = parseFloat(cart.sub_product_total) - parseFloat(price);
    } else {
        $('.add-price-selected-'+id).addClass('current');
        cart.sub_product_cart[id] = {"id":id, "title":title, "num":1,"price":price};
        cart.sub_product_total = parseFloat(cart.sub_product_total) + parseFloat(price);
    }

    var sub_product_select = 0;
    for (var k in cart.sub_product_cart) {
        if(cart.sub_product_cart[k] != '') {
            sub_product_select = 1;
        }
    }

    if(sub_product_select == 1) {
        $('#sub_product_tips').addClass('sub_product-current');
    } else {
        $('#sub_product_tips').removeClass('sub_product-current');
    }

    cart.count_show(0,0,"");
}

/**
 * 用户选中子商品
 * @method actives.userSubProduct
 * @param {Object} object
 */
actives.userSubProduct = function(object) {
    var data = object || '';
    if(data == '') {
        return false;
    }

    for(var i in data) {
        $('.add-price-selected-'+data[i]['id']).addClass('current');
    }
}

/**
 * 获得当前子产品数组id
 * @method actives.getCurrentSubProduct
 */
actives.getCurrentSubProduct = function() {
    var buycar = getCookie('buycar');
    buycar = product_weighing.buycartAddWeights(buycar);
    if(common.isNull(buycar)) {
        return '';
    }

    var goods = buycar.split("|");
    if(common.isOwnEmpty(goods)) {
        return '';
    }

    var arr = [];
    for(var i in goods) {
        var item = goods[i].split(',');
        var product = actives.cart[item[0]];
        if(!common.isOwnEmpty(product)) {
            var ids = product.sub_product_ids || '';
            ids = ids.toString().split(",");
            for(var j in ids ) {
               if (!arr, ids[j]) {
                   arr.push(ids[j]);
               }
            }
        }
    }

    return arr;
}

/**
 * 移除用户选择的子产品
 * 由于子产品的父商品不存在了，用户不能继续购买子产品, 需要自动移除子产品
 * @method actives.removeUserSelectedSubProduct
 */

actives.removeUserSelectedSubProduct = function() {
    var subProduct = actives.getCurrentSubProduct();
    for(var i in cart.sub_product_cart) {
        var pid = 0;
        var id = cart.sub_product_cart[i]['id'];

        for(var j in actives.subProduct) {
            if(actives.subProduct[j]['id'] == id) {
                pid = actives.subProduct[j]['pid'];
            }
        }

        if(!base.inArray(subProduct,pid)) {
            if(cart.sub_product_cart[i] != '') {
                cart.sub_product_total = parseFloat(cart.sub_product_total) - parseFloat(cart.sub_product_cart[i]['price']);
                cart.sub_product_cart[id] = '';
            }
        }
    }
}

/**
 * 加价购活动名称设置
 * @method actives.setAddPriceName
 * @param {Object} data 加价购商品列表数据
 * @param {Number} limit 最底限制金额
 */
actives.addPriceControl = function(object) {
    var object = object || '';

    if(object == '') {
        $('#cart-add-products').hide();
        return false;
    }

    $('#cart-add-products-wrap').show();

    var data = object.product;
    var limit = object.min_order_fee;
    var power = actives.addProductPower();
    var sum = 0, feeTotal = 0, tips = '', html = '',title = '';

    common.renderTpl('#cart-add-products','./cart/cart_add_products',{data: object.product});

    for(var i in data) {
        if(data[i].price == 0) {
            feeTotal++;
        }
        sum++;
        actives.add_price_cancel[data[i].id] = 0;
    }

    title = '兑&nbsp;&nbsp;&nbsp;&nbsp;换：';
    if(sum == 1) { //加价购只有一个商品
        if(feeTotal == 0) {
            tips = "商品买满"+limit+"加"+data[0].add_price+"元,就可以换取"+data[0].title;
        } else {
            title = '赠&nbsp;&nbsp;&nbsp;&nbsp;品：';
            tips = "商品买满"+limit+",就可以免费获得"+[i].title;
        }
    } else {
        if(feeTotal == 0) {
            tips = "商品买满"+limit+"元加指定金额,可换购指定水果";
        } else {
            tips = "商品买满"+limit+"元,就可以免费获得指定水果";
        }
        if(sum == feeTotal && cart.data.sub_products.length == 0) {
            title = '赠&nbsp;&nbsp;&nbsp;&nbsp;品：';
        }
    }

    if(object.vip_stauts == 1 && !common.isVip()) {
        tips += ',仅限会员哦';
    }

    actives.user_join_box = 1;
    $("#add_price_div").data('info',tips);
    $("#add_price_div").data('vip',object.vip_stauts);
    $("#add_price_div").css('display','block');
    $('#add_price_div').html(object.event_name);
    //$('.add-price-name-'+data[0].id).html(title);
    $('.add-price-model-1').show();
    $('#user-join-actives').show();
}

/**
 * 用户选择加价购商品
 * @method actives.selectAddProduct
 * @param {Number} id 商品id
 * @param {String} title 商品名称
 * @param {Number} prcie 商品价钱
 * @param {Number} kucan 商品库存
 */
actives.selectAddProduct = function(id, title, price, kucun) {
    if(parseInt(kucun) <= 0) {
        tipsBox.createAlertBox('你来晚了，'+title+'已经卖完了');
        return false;
    }

    if(!actives.addProductPower()) {
        tipsBox.createAlertBox('亲，你未达到加价购金额，加把油吧！')
        return false;
    }

    var vip = $('#add_price_div').data('vip');
    if(vip == 1 && !common.isVip()) {
        tipsBox.createAlertBox( $('#add_price_div').html() + ',仅限会员哦');
        return false;
    }

    var isSelected = $('.add-price-selected-'+id).hasClass('current');
    if(isSelected) {
        actives.add_price_cancel[id] = 1;
        cart.add_product_cart.selected--;
        cart.add_product_cart.cart[id] = '';
        $('.add-price-selected-'+id).removeClass('current');
        cart.add_product_cart.total = parseFloat(cart.add_product_cart.total) - parseFloat(price);

    } else {
        actives.add_price_cancel[id] = 0;
        cart.add_product_cart.selected++;
        $('.add-price-selected-'+id).addClass('current');
        cart.add_product_cart.cart[id] = {"id":id, "title":title, "num":1,"price":price};
        cart.add_product_cart.total = parseFloat(cart.add_product_cart.total) + parseFloat(price);
    }

    if(cart.add_product_cart.selected >= 1) {
        $('#add_price_div').addClass('add-price-join-current');
    } else {
        $('#add_price_div').removeClass('add-price-join-current');
    }
    cart.count_show(0,0,'add_price');
}

/**
 * 加价购操作
 * @method actives.addPriceOpera
 * @param {Object} object
 */
actives.addPriceOpera = function(object) {
    var object = object || '';
    if(object == '') {
        return false;
    }

    var data = object.product;
    var power = actives.addProductPower();
    if(!power) {
        cart.add_product_cart = { cart: {}, total: 0, selected:0 };
        $('#add_price_div').removeClass('add-price-join-current');
        $('.add-price-model-1 table').removeClass('current');
        return false
    }

    for(var i in data) {
        if(data[i].price == 0 && actives.add_price_cancel[data[i].id] == 0) { //0元,默认帮用户选择，加入购物车
             if (parseInt(data[i].kucun) >= 1) {
                 cart.add_product_cart.cart[data[i].id] = {
                     "id": data[i].id,
                     "title": data[i].title,
                     "num": 1,
                     "price": data[i].price
                 };
                cart.add_product_cart.total = parseFloat(cart.add_product_cart.total) + parseFloat(data[i].price);
                $('.add-price-selected-' + data[i].id).addClass('current');
                 cart.add_product_cart.selected++;
             }
        }
    }

    if(cart.add_product_cart.selected >= 1) {
        $('#add_price_div').addClass('add-price-join-current');
    } else {
        $('#add_price_div').removeClass('add-price-join-current');
    }
}

/**
 * 加价购的符合条件的用户
 * @method actives.addProductPower
 * @return boolen
 */
actives.addProductPower = function() {
    var add_product_total = parseFloat(cart.add_product_cart.total); //加价购总金额
    var special_fruit_total = parseFloat(cart.special_fruit_total); //特价总金额
    var fruit_total = cart.order_fruit_sum() - special_fruit_total - add_product_total; //加价购，兑换指定水果金额;
    if(fruit_total < Number(cart.data.add_price.min_order_fee)) {
        return false;
    } else {
        return true;
    }
}

/**
 * 加价购计算
 * @returns {number}
 */
actives.addProductCount = function() {
    if(cart.add_product_cart.selected == 0) {
        return 0;
    }

    if(!actives.addProductPower()) {
        var total = cart.add_product_cart.total;
        cart.add_product_cart.total = 0;
        cart.add_product_cart.selected = 0;
        for(var k in cart.add_product_cart.cart) {
            $('.add-price-selected-'+cart.add_product_cart.cart[k]['id']).removeClass('current');
            cart.add_product_cart.cart[k] = '';
        }
        $('#add_price_div').removeClass('add-price-join-current');
        return total.toFixed(2);
    } else {
        return 0;
    }
}

/**
 * 生成加价购id列表,以逗号(,)划分
 * @method actives.createAddProductIdList
 * @return String
 */
actives.createAddProductIdList = function(object) {
    if(object.selected <= 0) {
        return false
    }

    var list = '';
    for (var i in object.cart) {
        if(object.cart[i].id != undefined) {
            list += ','+object.cart[i].id;
        }
    }
    return list.substring(1);
}



/**
 * 活动启动提示控制
 * @method actives.tipsControl
 */
actives.tipsControl = function() {
    var i = 0;
    var sum = 9;

    $('.user-join-actives ul li').each(function() {
       if($(this).find('span').css('display') == 'none') {
            i++;
       }
    });
    if(i == sum ) {
        $('#cart-add-products-wrap').hide();
        $('.user-join-actives').hide();
    }
    if($('#sub_product_tips').css('display') == 'none' &&  $('#add_price_div').css('display') == 'none') {
        $('#cart-add-products-wrap').hide();
    }

    if($('#sub_product_tips').css('display') == 'block' &&  $('#add_price_div').css('display') == 'block') {
        $('#cart-add-products div:last-child').css('borderWidth','1px');
        $('#cart-add-products div:last-child').css('marginBottom','0px');
    }

    if($('#sub_product_tips').css('display') == 'none' &&  $('#add_price_div').css('display') == 'block') {
        $('#cart-add-products div:last-child').css('borderWidth','0px');
        $('#cart-add-products div:last-child').css('marginBottom','-10px');
    }
}

/**
 * 计算正常商品的总价
 * @method normalGoodsTotal
 */
actives.normalGoodsTotal = function() {
    var buycar = getCookie('buycar');
    buycar = product_weighing.buycartAddWeights(buycar);
    if(common.isNull(buycar)) {
        return 0;
    }

    var goods = buycar.split("|");
    if(common.isOwnEmpty(goods)) {
        return 0;
    }

    var total_fee = 0;
    for(var i in goods) {
        var item = goods[i].split(',');
        var product = product_list[item[0]];
        if(!common.isOwnEmpty(product)) {
            if(actives.isWeights(product.id)) { //称重产品
                product.price = item[3];
                product.num = item[2];
            }
            total_fee += parseFloat(product.price) * parseInt(product.num);
        }
    }

    return base.setNumberIntegral(total_fee);
}

/**
 * 指定商品的总价
 * @method aactives.appointGoodsTotal
 * @param {String} ids 指定id字符串
 */
actives.appointGoodsTotal = function(ids) {
    var ids = ids.toString().split(",");
    var buycar = getCookie('buycar') || '';
    buycar = product_weighing.buycartAddWeights(buycar);
    var data = { titles: '', num: 0, total_fee: 0 };

    if(common.isNull(buycar)) {
        return data;
    }

    var goods = buycar.split("|");
    if(common.isOwnEmpty(goods)) {
        return data;
    }

    for(var i in goods) {
        var item = goods[i].split(',');
        var product = product_list[item[0]];
        if(!common.isOwnEmpty(product)) {
            for(var j in ids) {
                if(ids[j] == product.pid) {
                    if(actives.isWeights(product.id)) { //称重产品
                        product.price = item[3];
                        product.num = item[2];
                    }
                    data.num += product.num;
                    data.total_fee += parseFloat(product.price) * parseInt(product.num);
                }
            }
        }
    }
    data.total_fee = base.setNumberIntegral(data.total_fee);

    for(var i in product_list) {
        for(var j in ids) {
            if(product_list[i].pid == ids[j]) {
                data.titles += product_list[i].title+',';
            }
        }
    }
    return data;
}


/**
 * 活动统计
 * @method actives.count
 */
actives.count = function() {
    cart.data.cart_user_league = user.userBase.league_id; //临时数据
    if(cart.data.cart_environment == 1 && cart.data.cart_user_league != _headOffice) {
        cart.data.showWeixin = 0;
    }

    cart.bag_skus = result.data.bag_skus;
    show_activty_tip(result);
    cart.data.sub_products = result.data.sub_products;

    var sub_product_tips = '';
    for(var i=0; i < result.data.sub_products.length; i++) {
        sub_product_tips += result.data.sub_products[i]['subtitle']+"<br/>";
    }
    if(sub_product_tips != '') {
        actives.user_join_box = 1;
        $('#user-join-actives').show();
        $('#sub_product_tips').data('info',sub_product_tips);
        $('#sub_product_tips').css('display','block');
    } else {
        $('#sub_product_tips').hide();
    }

    cart_group.groupWeiXinPlay();
    cart.show_sub_product(result.data.sub_products);
}

/**
 * 活动提示框
 * @method actives.showEventInfo
 * @param {String} id 元素id
 */
actives.showEventInfo = function(id) { //活动信息
    var info = $('#'+id).data('info');
    tipsBox.createAlertBox(info);
}


/**
 * 收货地址管理
 */
var user_address = {};
user_address.status = "list";
user_address.save_status = "new";
user_address.num = 0;
user_address.data = [];
user_address.map_model = 1;    //1为加盟商地图模式，2为加盟商手动输入模式

var order_or_cart = 0;        //0为购物车地址，1为订单列表地址
var order_num = 0;            //订单编号
user_address.list = function (from) {
    map_address.map_is_loaded = 0;    //地图重设
    map_address.change_center = 0;    //强制改变地图中心
    user_address.status = "list";
    var url = api_host + "/Api/Users/address_list";
    var openid = user.userBase.bingo_openid;
    if (openid == undefined || openid == null || openid.length == 0) {
        return false;
    }
    var data = {
        bingo_access_token: openid
        , bingo_openid: openid
        , league_id: user.userBase.league_id
        , branch_id: user.userBase.branch_id
    };
    $.ajax({type: 'post', url: url, data: data, dataType: 'json', success: function (result) {
        // console.log(order_or_cart);
        if(order_or_cart == 1){         //顶单列表
            if (from == "add_new") {
                user_address.close();
            }else if(from == "order"){
                user_address.data = result.data.address;
                user_address.num = result.data.address.length;
                user_address.select_delivery_list(0);
            }else if(from == "buy_cart"){
                user_address.data = result.data.address;
                user_address.num = result.data.address.length;
                var html = template('address_list', result);
                $("#user_addr_admin").html(html);

                navigation.commonFooterTpl("新增收货地址", "javascript:void(0);","user_address.add('')");   //设置底部按钮
            }
        }else{
            user_address.map_model = result.data.map_model;
            if (result.data.address.length <= 0) {      //没有收货地址
                user_address.add('');
                if (from == "add_new") {
                    user_address.close();
                    return false;
                }
            } else {
                user_address.data = result.data.address;
                user_address.num = result.data.address.length;
                if (from == "add_new") {
                    user_address.select_delivery_list(0);
                    return false;
                }
                var html = template('address_list', result);
                $("#user_addr_admin").html(html);

                navigation.commonFooterTpl("新增收货地址", "javascript:void(0);","user_address.add('')");   //设置底部按钮

                //选择外面购物车的地址
                var address_submitid = $("#address_submitid").val();
                $("#my-address-"+address_submitid).addClass('my-address-item-cur');
            }
        }
    }});
};
user_address.delete = function (id) {
    tipsBox.createConfirmBox('确定删除该地址吗', 'user_address.sure_delete', id, '确定');
};

user_address.sure_delete = function (id) {
    var url = api_host + "/Api/Users/address_delete";
    var openid = user.userBase.bingo_openid;
    if (openid == undefined || openid == null || openid.length == 0) {
        return false;
    }
    var data = {
        bingo_access_token: openid
        , bingo_openid: openid
        , address_id: id
    };
    $.ajax({type: 'post', url: url, data: data, dataType: 'json', success: function (result) {
        if (result.status == 1) {
            user_address.list('buy_cart');
            tipsBox.hideTipsBox();
        }
    }});

};

user_address.delivery_admin = function () {
    if (user_address.status == "list") {
        user_address.status = "edit";
        $("#address_admin_btn").text("完成");
        $(".my-address-opera-inner").show();
    } else if (user_address.status = "edit") {
        user_address.status = "list";
        $("#address_admin_btn").text("管理");
        $(".my-address-opera-inner").hide();
    }
};
user_address.close = function () {
    order_list.showMenu(1);
    // console.log(order_num);
    $("#user_addr_admin").hide();
    $('#app-header').show();
    if(order_or_cart == 1){
        $('#view_page').show();
        $('#common-footer').show();
        $("html,body").scrollTop($('#item-'+order_num).offset().top);
    }else{
        $('.cart-footer').show();
        $("#buy_cart_div").show();
        $("html,body").scrollTop($('.address-manage').offset().top);
        $('.snap-content').removeClass('user_addr_admin_bottom');
    }

};
user_address.show = function () {
    $("html,body").scrollTop(0)
    $('#app-header').hide();
    $('.cart-footer').hide();
    $('.snap-content').addClass('user_addr_admin_bottom');
    $("#buy_cart_div").hide();
    $("#user_addr_admin").show();
    $('#user_addr_admin').css('min-height', ($(window).height() - 50) + "px");
    user_address.list("buy_cart");

    //按钮点击统计
    common.buttonClikcStatistics("car","car_address","选择地址");
};

user_address.order_address_show = function(orderid,addressid){             // 订单收货信息修改
    order_or_cart = 1;
    order_num = orderid;
    $('#view_page').hide();
    $('#common-footer').hide();

    $('.snap-content').css('padding-bottom','0px');
    $("#user_addr_admin").show();
    $('#user_addr_admin').css('min-height', ($(window).height() - 50) + "px");

    user_address.status = "list";

    var url = api_host + "/Api/Users/address_list";
    var openid = user.userBase.bingo_openid;
    if (openid == undefined || openid == null || openid.length == 0) {
        return false;
    }
    order_list.showMenu(0);
    var data = {
        bingo_access_token: openid
        , bingo_openid: openid
        , league_id: user.userBase.league_id
        , branch_id: user.userBase.branch_id
    };
    $.ajax({type: 'post', url: url, data: data, dataType: 'json', success: function (result) {
        if (result.data.address.length <= 0) {      //没有收货地址
            user_address.add('');
        } else {
            user_address.data = result.data.address;
            var html = template('address_list', result);
            $("#user_addr_admin").html(html);

            navigation.commonFooterTpl("新增收货地址", "javascript:void(0);","user_address.add('')");   //设置底部按钮

            if(addressid != 0){    //选中进来的地址
                $("#my-address-"+addressid).addClass('my-address-item-cur');
            }
        }
    }});
}

user_address.add = function (item) {
    user_address.save_status = "new";
    if(user_address.map_model == 1){          //加盟商地图模式
        var url = api_host + "/Api/league/get_user_league";
    }else{
        var url = api_host + "/Api/league/get_delivery_area";
    }
    var openid = user.userBase.bingo_openid;
    if (openid == undefined || openid == null || openid.length == 0) {
        return false;
    }
    var data = {
        bingo_access_token: openid
        , bingo_openid: openid
    };
    $.ajax({type: 'post', url: url, data: data, dataType: 'json', success: function (result) {
        if(user_address.map_model == 1){          //加盟商地图模式
            result.addr1 = result.data.display_name;
            var html = template('address_add', result);
        }else{
            var city = select_area.city_list[user.userBase.city_code];
            if (city != undefined) {
                result.addr1 = city.replace("市", "") + user.userBase.short_name;
            } else {
                result.addr1 = user.userBase.short_name;
            }
            var html = template('address_add_old', result);
        }
        $("#user_addr_admin").html(html);
        $('#user_addr_admin').css('min-height', $(window).height() + "px");

        navigation.commonFooterTpl("保存", "javascript:void(0);","user_address.save()");   //设置底部按钮

        if (item != "") {       //修改旧地址
            $("#address_id").val(item.id);
            $("#user_name").val(item.user_name);
            $("#user_name").css('color','#777');
            $("#user_tel").val(item.user_tel);
            $("#user_tel").css('color','#777');
            if(user_address.map_model == 1){
                $("#user_addr2").text(item.address);
                $("#user_addr2").css('color','#6fbfd9');
                $('.select-area-box > div .user-input-address').css('color', '#6fbfd9');
                if(item.baidu_x != "" || item.baidu_x != undefined || item.baidu_x != null){
                    $('#coords_x').val(item.baidu_x);
                    $('#coords_y').val(item.baidu_y);
                }
                if(item.addr_doorplate != ''){
                    $('#doorplate_no').val(item.addr_doorplate);
                    $("#doorplate_no").css('color','#777');
                }
            }else{
                if(item.delivery_area_id == '' || item.delivery_area_id == undefined || item.delivery_area_id == null){
                    $("#user_addr2").val("请选择");
                }else{
                    $("#admin_my_addr2").val(item.delivery_area_id);
                    $("#user_addr2").text(item.area_name);
                    $('.select-area-box > div').css('color', '#6fbfd9');
                    $('.select-area-box > div span').css('color', '#6fbfd9');
                }
                $("#address_display").html(item.address);
                $("#address_display").css('color','#333');
                $("#address").val(item.address);
                $("#address").css('color','#777');
            }
            if(item.tag != '' || item.tag !=null){
                $("#tag").val(item.tag);
                $("#tag").css('color','#777');
            }
            if(item.tag == '' || item.tag ==null){
                $("#tag").val("家/公司");
                $("#tag").css('color','#afafaf');
            }
            if (item.is_default == 1) {
                $("#is_default").attr("checked", 'true');
                $('.address-new-add').addClass('current');
            }
        }
    }});
};

//选中默认地址
user_address.default_address = function () {
    if ($('.address-new-add').hasClass('current')) {
        $('.address-new-add').removeClass('current');
    } else {
        $('.address-new-add').addClass('current');
    }
}

//选择一个区域
user_address.select_a_addr = function () {

    var a = $("#admin_my_addr2 option").not(function () {
        return !this.selected
    }).text();
    var value = $('#admin_my_addr2').val();
    if (value == 0) {
        $('.select-area-box > div').css('color', '#999');
        $('.select-area-box > div span').css('color', '#999');
    } else {
        $('.select-area-box > div').css('color', '#6fbfd9');
        $('.select-area-box > div span').css('color', '#6fbfd9');
    }
    $("#user_addr2").text(a);
};

user_address.select_focus = function () { //select存在选不上bug
    $('#user_name').blur();
    $('#user_tel').blur();
    $('#address').blur();
    $('#tag').blur();
    $('#is_default').blur();
    $('#admin_my_addr2').focus();
}

//保存地址
var addr_saveing = 0;
user_address.save = function () {

    var status = user_address.checkAddressData();
    if(status == -1){
        return false;
    }

    if (addr_saveing == 1) {
        return false;
    }

    var tag_text = $("#tag").val();
    if(tag_text == "家/公司"){
        tag_text = "";
    }
    addr_saveing = 1;
    var url = api_host + "/Api/Users/address_add";
    var openid = user.userBase.bingo_openid;
    if (openid == undefined || openid == null || openid.length == 0) {
        return false;
    }
    if(user_address.map_model == 1){      //地图模式
        var data = {
            bingo_access_token: openid
            , bingo_openid: openid
            , user_name: $("#user_name").val()
            , user_tel: $("#user_tel").val()
            , address: $("#user_addr2").html()
            , tag: tag_text
            , is_default: $('input[name="is_default"]:checked').val() == 1 ? 1 : 0
            , baidu_x: $('#coords_x').val()
            , baidu_y: $('#coords_y').val()
            , addr_doorplate: $("#doorplate_no").val()
            , league_id: user.userBase.league_id
            , branch_id: user.userBase.branch_id == "" ? 'NULL' : user.userBase.branch_id
        };
    }else{        //手动填写模式
        var data = {
            bingo_access_token: openid
            , bingo_openid: openid
            , area_name: $("#user_addr2").html()
            , user_name: $("#user_name").val()
            , user_tel: $("#user_tel").val()
            , delivery_area_id: $("#admin_my_addr2").val() //修改地址需要注释
            , address: $("#address").val()
            , tag: $("#tag").val()
            , is_default: $('input[name="is_default"]:checked').val() == 1 ? 1 : 0
            , league_id: user.userBase.league_id
            , branch_id: user.userBase.branch_id == "" ? 'null' : user.userBase.branch_id
        };
    }
    var from = "add_new";
    if ($("#address_id").val() > 0) {
        url = api_host + "/Api/Users/address_edit";
        data.address_id = $("#address_id").val();
        from = "buy_cart";
    }
    if(order_or_cart == 1){
        from = "order";
    }

    $.ajax({type: 'post', url: url, data: data, dataType: 'json', success: function (result) {
        addr_saveing = 0;
        if (result.status == 1) {
            user_address.list(from);
            map_address.map_is_loaded = 0;         //地图重设
        } else {
            alertBox('.alert-box', result.data);
        }
    }});
};

/**
 * 检查收货地址是否可以提交
 * @method user_address.checkAddressData
 * return {Number}
 */
user_address.checkAddressData = function(){

    if ($("#user_name").val() == undefined || $("#user_name").val() == "" || $("#user_name").val() == "请输入收货人姓名") {
        alertBox('.alert-box', '请输入姓名');
        return -1;
    }
    if ($("#user_name").val().length > 10) {
        alertBox('.alert-box', '姓名不能超过10个字');
        return -1;
    }
    if ($("#user_tel").val() == undefined || $("#user_tel").val() == "" || $("#user_tel").val() == "请输入手机号码") {
        alertBox('.alert-box', '请输入联系电话');
        return -1;
    }
    if ($("#user_tel").val().length > 20) {
        alertBox('.alert-box', '联系电话不能超过20个字');
        return -1;
    }
    if ($("#user_tel").val().length != 11) {
        alertBox('.alert-box', '请输入11位手机号码');
        return -1;
    }

    var reg = /^13[\d]{9}$|^14[0-9]\d{8}|^15[0-9]\d{8}$|^17[0-9]\d{8}|^18[0-9]\d{8}$/g;
    if (!reg.test($("#user_tel").val())) {
        alertBox('.alert-box', '输入的手机号码有误');
        return -1;
    }
    if(user_address.map_model == 1){
        if ($("#user_addr2").html() == "请选择" || $("#user_addr2").html() == "") {
            alertBox('.alert-box', '请选择收货地址');
            return -1;
        }
        if ($("#user_addr2").html().length > 50) {
            alertBox('.alert-box', '具体地址不能超过50个字');
            return -1;
        }
        if($("#doorplate_no").val() == undefined || $("#doorplate_no").val() == '' || $("#doorplate_no").val() == "请输入具体楼号-门牌"){
            alertBox('.alert-box','请输入具体楼号-门牌');
            return -1;
        }
    }else{
        if ($("#address").val() == undefined || $("#address").val() == "" || $("#address").val() == "请输入具体地址") {
            alertBox('.alert-box', '请输入具体地址');
            return -1;
        }
        if ($("#address").val().length > 50) {
            alertBox('.alert-box', '具体地址不能超过50个字');
            return -1;
        }
        if ($("#admin_my_addr2").val() == "0") {
            alertBox('.alert-box', '请选择配送地区');
            return -1;
        }
    }
    if ($("#tag").val() !== undefined && $("#tag").val() !== "" && $("#tag").val().length > 4) {
        alertBox('.alert-box', '标签不能超过4个字');
        return -1;
    }
}

//选择一个地址
user_address.select_delivery_list = function (index) {
    var item = user_address.data[index];
    if (item == undefined) {
        return false;
    }
    if (user_address.status == "list") {
        user_address.show_in_cart(item,1,1);
        user_address.close();
    } else if (user_address.status == "edit") {
        user_address.add(item);
    }
};
/*
 *返回购物车地址或订单列表地址
*/
user_address.show_in_cart = function (item,sta,addresssta) {
    if(item.area_name == undefined || item.area_name == null || item.area_name == ''){
        item.area_name = "";
    }
    if(item.addr_doorplate == undefined || item.addr_doorplate == null || item.addr_doorplate == ''){
        item.addr_doorplate = "";
    }
    if(order_or_cart == 1){      //订单列表返回地址
        $("#modify-realname-"+order_num).text(item.user_name);
        $("#modify-tel-"+order_num).text(item.user_tel);
        $("#user_addr_"+order_num).text(item.address+item.addr_doorplate);
        $("#address_id-"+order_num).val(item.id);
        $("#address_click-"+order_num).attr("onclick","user_address.order_address_show(" + order_num + "," + item.id + ")");
    }else{
        $("#new-address").hide();
        $("#has-default-address").show();
        // if(sta == 0){
        //     cart.data.AddrVo.fee_free = item.fee_free;
        //     cart.data.AddrVo.fee = item.fee;
        // }
        cart.count_show(0, 0, "");
        var html = '<p>' + item.user_name + '&nbsp;&nbsp;&nbsp;' + item.user_tel + '</p><p class="ft-color">' + item.area_name + item.address + item.addr_doorplate + '</p>';
        $("#has-default-address").html(html);
        $("#realname").val(item.user_name);

        if(item.user_tel != undefined){
            $("#tel").val(item.user_tel);
            $("#ziti_tel").val(item.user_tel);
        }

        $("#addr1").val(user.userBase.short_name);
        if(addresssta == 0){    //car取得的默认地址
            $("#address_submitid").val(item.address_id);
        }else{
            $("#address_submitid").val(item.id);
        }

        if(user_address.map_model == 1){
            $("#addr2").val('');
        }else{
            $("#addr2").val(item.area_name);
        }
        $("#addr3").val(item.area_name+item.address+item.addr_doorplate);
        if(item.baidu_x == undefined || item.baidu_x == null || item.baidu_x == ''){
            item.baidu_x = "";
            item.baidu_y = "";
        }
        $("#maplng").val(item.baidu_x);
        $("#maplat").val(item.baidu_y);
    }
}


/**
 * 编辑收货地址，高德地图
 */
var map_address = {};
map_address.timerTaskt = null;
map_address.service_area_status = 1;
map_address.change_center = 0; //是否强制修改了中心点
map_address.userSwtich = "";  //上次分店区域
map_address.map_is_loaded = 0;
map_address.map_is_amap = 0;
/**
 * 打开地图的初次判断及处理
 * @method map_address.import_baidu_map
 */
map_address.import_baidu_map = function () {

    var city = select_area.city_list[user.userBase.city_code];
    $('#user_name').blur();
    $('#user_tel').blur();
    $('#address').blur();
    $('#tag').blur();
    $('#is_default').blur();

    if (map_address.map_is_loaded == 0) {     //地图重设
        var html = template('map_address_create', {});
        $('#import_baidu_map').html(html);

        $("#buy_cart_div").hide();
        $("#user_addr_admin").hide();
        $('.map-loading-wrap').show();
        $('.map-loading-box').show();
        $('#import_baidu_map').show();

        //获取加盟商信息
        var openid = user.userBase.bingo_openid;
        var url = api_host + "/Api/league/get_one_user_area";     //获取用户所在区域的加盟商信息
        var data = {bingo_access_token: openid, bingo_openid: openid};
        $.ajax({type: 'post', url: url, data: data, dataType: 'json', success: function (result) {
            map_address.get_userLeague = result;    //保存加盟商信息
            // console.log("加盟商信息：",map_address.get_userLeague);
            select_area.amapStatus = 0;
            map_address.create_map_html();    //定位
            map_address.map_is_loaded = 1;
        }});
    } else {
        $('#user_addr_admin').hide();
        $('#import_baidu_map').show();
        if($("#user_addr2").html() != "请选择"){     //已经选了地址
            var addr2 = $('#user_addr2').html();
            var coords_x = $("#coords_x").val();
            var coords_y = $("#coords_y").val();
            if(map_address.map_is_amap == 1){      //高德坐标
                baidu_map.window.panto(coords_x,coords_y);
            }else{
                baidu_map.window.geocoder(addr2);
            }
        }
    }
}

/**
 * 向子框架写入地图地址文件并带入参数
 * @method map_address.create_map_html
 */
map_address.create_map_html = function (cityName) {
    var city = (cityName == undefined) ? select_area.city_list[user.userBase.city_code] : cityName;
    if(browser.versions.iPhone || browser.versions.iPad || browser.versions.ios) {
        //防止IOS重复获取地理位置，IOS使用微信提供的地理位置
        if(_point == null || _point.longitude == "" || _point.latitude == ""){
            $('#baidu_map').attr('src', './extend/map/create_address.php?city=' + city + '&lng=0&lat=0');
        }else{
            $('#baidu_map').attr('src', './extend/map/create_address.php?city=' + city + '&lng=' + _point.longitude + '&lat=' + _point.latitude);
        }
    }else{
        $('#baidu_map').attr('src', './extend/map/create_address.php?city=' + city + '&lng=0&lat=0');
    }
}

/*
 * 高德地图自动查询框，编码类型对照：
 * 120000 商务住宅;商务住宅相关;商务住宅相关 | 130100 政府机构及社会团体;政府机关;政府机关相关 | 130101 政府机构及社会团体;政府机关;国家级机关及事业单位 | 190100 地名地址信息;行政地名;行政地名 | 141201 科教文化服务;学校;高等院校 | 141202 科教文化服务;学校;中学 | 141203 科教文化服务;学校;小学 | 141206 科教文化服务;学校;职业技术学校 | 090100 医疗保健服务;综合医院;综合医院 | 120100 商务住宅;产业园区;产业园区 | 120200 商务住宅;楼宇;楼宇相关 | 120201 商务住宅;楼宇;商务写字楼 | 120202 商务住宅;楼宇;工业大厦建筑物 | 120203 商务住宅;楼宇;商住两用楼宇 | 120300 商务住宅;住宅区;住宅区 | 120301 商务住宅;住宅区;别墅 | 120302 商务住宅;住宅区;住宅小区 | 120303 商务住宅;住宅区;宿舍 | 120304 商务住宅;住宅区;社区中心 | 190107 地名地址信息;行政地名;街道级地名 | 190108 地名地址信息;行政地名;村庄级地名 | 190109 地名地址信息;行政地名;村组级地名
 * @method map_address.amapAutocomplete
 */
map_address.amapAutocomplete = function(){
    var city = (select_area.city_list[user.userBase.city_code] == undefined) ? select_area.selectCityArea.cityCode : select_area.city_list[user.userBase.city_code];
    var key = $("#suggestId").val();
    if(key == ""){
        $("#autoTipsList ul").html("");
    }
    AMap.service(["AMap.Autocomplete"], function() {    //加载正地理编码插件
        var auto = new AMap.Autocomplete({
            type: '120000|130100|130101|190100|141201|141202|141203|141206|090100|120100|120200|120201|120202|120203|120300|120301|120302|120303|120304|190107|190108|190109',
            city: city,
            citylimit: true
        });
        auto.search(key, function(status, result){
            if(status == "complete"){
                // console.log(result);
                var tips = result.tips;
                if(result.info == "OK" && tips.length > 0){
                    var html = [];
                    for(var i = 1,len = tips.length; i < len; i++){
                        if(tips[i].location == undefined){
                            html[i] = '<li><a href="javascript:void(0);" onclick="map_address.submit_address(\''+ tips[i].name +'\',\'\',\'\',\'\');">' + tips[i].name + '<span>' + tips[i].district + '</span></li>';
                        }else{
                            html[i] = '<li><a href="javascript:void(0);" onclick="map_address.submit_address(\''+ tips[i].name +'\',\'\',\'' + tips[i].location.lng +'\',\'' + tips[i].location.lat + '\');">' + tips[i].name + '&nbsp;&nbsp;<span>' + tips[i].district + '</span></li>';
                        }
                    }
                    $("#autoTipsList ul").html(html.join(""));
                }else{
                    $("#autoTipsList ul").html("");
                }
            }else if(status == "no_data"){
                var html = '<li class="seek-null">找不到这个地址</li>'
                $("#autoTipsList ul").html(html);
            }
        });
    });
}

/**
 * 判断用户的经纬度是否在服务范围
 * @param {String} address 地址
 * @param {String} longitude 经度
 * @param {String} latitude 纬度
 */
map_address.service_area = function (address, longitude, latitude) {
    var openid = user.userBase.bingo_openid;
    var url = api_host + "/Api/league/get_user_auto_league";
    var data = {
        bingo_access_token: openid
        ,bingo_openid: openid
        ,longitude: longitude
        ,latitude: latitude
        ,set_user_league: 0
        ,type: "baidu"
    };
    $.ajax({type: 'post', url: url, data: data, dataType: 'json', success: function (result) {
        var resultData = result.data;
        if (result.status == 1) {
            var thisArea = resultData.short_name;    //定位区域的分店
            var myArea = user.userBase.short_name == undefined ? select_area.selectCityArea.areaName : user.userBase.short_name;       //用户分店
            var user_addr2 = $('#user_addr2').html();
            var userLeagueInfo = map_address.get_userLeague.data;
            // console.log(thisArea,myArea,user.userBase.league_center_point,map_address.change_center,address);
            //2. wlq 如果地理位置没有落在 当前分店内 则以分店为中心显示地图
            if(user_addr2 == "请选择"){
                if (thisArea != myArea && map_address.change_center == 0 && address != 0){
                    //当前分店存在中心点坐标
                    if(user.userBase.league_center_point != 0){
                        var tmp_point = user.userBase.league_center_point.split(",");
                        baidu_map.window.panto(tmp_point[0], tmp_point[1]);
                    }else{     //当前分店不存在中心点坐标
                        baidu_map.window.geocoder(userLeagueInfo.abholung_address);
                    }
                    map_address.change_center = 1;
                    return false;
                }
            }
            switch (parseInt(resultData.status)){
                case 0:
                    //在服务区域里但不在当前区域
                    if(map_address.userSwtich == thisArea && map_address.userSwtich != ""){     //上次跟这次一样
                        break;
                    }

                    var btn = '去' + resultData.short_name + '看看';
                    var param = resultData.short_name + ',' + resultData.league_id + ',' + resultData.branch_id;
                    var tips = '你的定位区域为' + resultData.short_name + '，你购买区域为' + myArea + '，是否继续填写地址。';
                    tipsBox.createConfirmBox(tips, 'select_area.set_user_league', param, btn);
                    $('#tips-box div.confirm-wrap table tr td:first-child a').html('继续填写');
                    break;
                case -1:
                    //不在配送区域
                    var city_code = userLeagueInfo.city_code;
                    var ser_tel = userLeagueInfo.ser_tel;
                    var tips = '你选择的地址不在配送范围内，下单可能会视为无效订单，你可以联系店长询问是否配送。<span class="thisarea-tel">'+myArea+'店：' + city_code + '-' + ser_tel +'</span>';
                    tipsBox.createConfirmBox(tips,'tipsBox.hideTipsBox','','联系店长');
                    $('#tips-box div.confirm-wrap table tr td:last-child a').attr('href', 'tel:'+ser_tel);

                    break;
                case 1:
                    //在当前服务区域
                    break;
            }
            map_address.userSwtich = thisArea;    //保存为上次的分店
        } else {
            tipsBox.createAlertBox(resultData);
        }
    }});
}

/**
 * 用户选择一个地址
 * @method map_address.submit_address
 * @param {String} title POI标题
 * @param {String} address POI详细地址
 * @param {String} lng POI经度
 * @param {String} lat POI纬度
 */
map_address.submit_address = function(title,address,lng,lat){
    $('#autoTipsList ul').html("");
    var address = address+title;
    $('#user_addr2').html(address);
    map_address.back_address_eixt();
    $('#coords_x').val(lng);     //保存经度
    $('#coords_y').val(lat);      //保存维度
    map_address.map_is_amap = 1;
}

/**
 * 关闭地图,返回到收货地址编辑界面
 * @method map_address.back_address_eixt
 */
map_address.back_address_eixt = function(){
    if(select_area.amapStatus == 1){
        //商城前面新增的收货地址
        $('.autocomplete').hide();
        $('#importAmapMap').hide();
        $("#userAddrAdmin").show();
        $('#app-header').show();
        $('#app-footer').show();
        $('#app_content').css('padding-bottom','50px');
        return false;
    }
    $('.autocomplete').hide();
    $('#import_baidu_map').hide();
    $("#user_addr_admin").show();
}

/**
 * 用户定位失败，手动定位收货地址
 * @method map_address.go_map_address
 */
map_address.go_map_address = function(){
    var city_code = map_address.get_userLeague.data['city_code'];
    var abholung_address = map_address.get_userLeague.data['abholung_address'];
    var city = select_area.city_list[user.userBase.city_code]
    baidu_map.window.go_league_address(abholung_address);     //根据加盟商地址定位到加盟商
    $('#address-city').html(city.replace("市", ""));
}

/**
 * 用户点击查找小区/大厦/街道等
 * @method map_address.input_address
 */
map_address.input_address = function(){
    $('#suggestId').val("");
    $('.autocomplete').show();
    $('#suggestId').focus();
}

/**
 * 取消自动查询输入
 * @method map_address.cancel_input
 */
map_address.cancel_input = function(){
    $("#suggestId").blur();
    $('#suggestId').val("");
    $("#autoTipsList ul").html("");
    $('.autocomplete').hide();
}

/**
 * 删除自动查询的文本框内容
 * @method map_address.delete_text
 */
map_address.delete_text = function(){
    $("#autoTipsList ul").html("");
    $(".input-address-text input").val("");
    $('.tangram-suggestion-main').css("display","none!important");
    $(".input-address-text input").focus();
}

/**
 * 提示用户开启GPS功能
 * @method map_address.tips_user_open_GPS
 */
map_address.tips_user_open_GPS = function() {
    var tips = '';
    if (browser.versions.iPhone || browser.versions.iPad || browser.versions.ios) {
        tips = '请在系统设置中开启定位服务，设置->隐私->定位服务->开启';
    } else {
        tips = '请在系统设置中开启定位服务，设置->位置信息->允许使用我的位置信息->开启';
    }
    tipsBox.createAlertBox(tips);
}


var aftersale = {};
aftersale.apply_return_btn_status = 1;
aftersale.product_valuation = [];       //已修改过评价的商品
aftersale.product = {};
/**
 * 售后服务入口
 * @method aftersale.entrance
 * @param {Number} uid 用户id
 * @param {Number} oid 订单id
 */
aftersale.entrance = function(uid, oid) {
    var url = api_host + "/Api/Order/get_order_info";
    var data={ user_id : uid, order_id : oid };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        result.data.openid = user.userBase.bingo_openid;
        common.renderTpl("#app_content",'after_sale/entrance',result.data);
        aftersale.getOrderList(oid);
        common.loaded(0);
    }});
}

/**
 * 获得订单购买详细水果
 * @method aftersale.getOrderList
 * @param {Number} oid 订单id
 */
aftersale.getOrderList = function(oid) {
    var url = api_host + "/Api/AfterSale/get_share_info";
    var openid = user.userBase.bingo_openid;
    var data = { bingo_access_token: openid ,bingo_openid: openid ,order_id: oid };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
       if(result.status == 1) {
           common.renderTpl("#order_list",'after_sale/order_list',result.data);
       }
    }});
}

/**
 * 显示订单里的购买水果
 * @method aftersale.shareFruitShow
 */
aftersale.shareFruitShow = function() {
    var show = $('#shareShow').val();
    $('.aftersale-header h2 i').removeClass('icon-angle-up');
    $('.aftersale-header h2 i').removeClass('icon-angle-down');
    if(show == 1) {
        $('.aftersale-header h2 i').addClass('icon-angle-up');
        $('.aftersale-header ul').hide();
        $('#shareShow').val(0);
    } else {
        $('.aftersale-header h2 i').addClass('icon-angle-down');
        $('.aftersale-header ul').show();
        $('#shareShow').val(1);
    }
}

/**
 * 获取订单评价页面信息
 * @method aftersale.get_appraise_info
 * @param {String} orderno 订单号
 * @returns {boolean}
 */
aftersale.get_appraise_info = function(orderno) {
    var url = api_host + "/Api/AfterSale/get_appraise_info";
    var openid = user.userBase.bingo_openid;
    var data = { bingo_access_token: openid, bingo_openid: openid, orderno: orderno };
    $.ajax({type: 'post', url: url, data: data, dataType: 'json', success: function(result) {
        if(result.status != 1) {
            result.orderno = orderno;
            common.renderTpl("#app_content",'after_sale/consulting',result);
            common.loaded(1);
            return false;
        }

        aftersale.product_valuation = [];       //清空变量
        result.data.order.orderno = orderno;
        aftersale.product.list = result.data.product;
        common.renderTpl("#app_content",'after_sale/appraise',result.data);
        common.loaded(1);
    }});
}

/**
 * 产品点赞按钮
 * @method aftersale.fruitLikeBtn
 * @param {String} pid 产品pid
 * @param {String} lid 产品lid
 * @param {Number} type 点赞类型
 */
aftersale.fruitLikeBtn = function(pid,lid,type) {
    tipsBox.hideTipsBox();
    var like_score = $("#like_score").val();
    var likeDoom = (type == 1) ? '#like-btn-'+pid+' i' : '#dontlike-btn-' + pid + ' i';
    var order_id = $('#order_id').val();
    var currentDoom = "";
    var cantDoom1 = "";
    var cantDoom2 = "";
    switch(Number(type)){
        case 1:
            var currentDoom = "#like-btn-" + pid;
            var cantDoom1 = "#soso-btn-" + pid;
            var cantDoom2 = "#dontlike-btn-" + pid;
            break;
        case 2:
            var currentDoom = "#soso-btn-" + pid;
            var cantDoom1 = "#like-btn-" + pid;
            var cantDoom2 = "#dontlike-btn-" + pid;
            break;
        case 3:
            var currentDoom = "#dontlike-btn-" + pid;
            var cantDoom1 = "#soso-btn-" + pid;
            var cantDoom2 = "#like-btn-" + pid;
            break;
    }
    var url = api_host + "/Api/AfterSale/prais";
    var openid = user.userBase.bingo_openid;
    var data = {
        bingo_access_token: openid
        ,bingo_openid: openid
        ,order_id: order_id
        ,pid: pid
        ,lid: lid
        ,bingo_appid: config.appid
        ,appraise_like: type
    };
    $.ajax({type: 'post', url: url, data: data, dataType: 'json',success: function(result){
        if(result.status != 1) {
            tipsBox.createAlertBox(result.data);
            return false;
        }
        $(currentDoom).removeAttr('onclick').find("span").addClass('current').next("p").css('color','#6fbfd9');
        $(cantDoom1).removeAttr('onclick').find("span").addClass('dont').next("p").css('color','#ddd');
        $(cantDoom2).removeAttr('onclick').find("span").addClass('dont').next("p").css('color','#ddd');

        $('#appraise-tip-box').addClass('appraise-tips-active');
        $('#appraise-tip-box').text('感谢你的评分，获得' + like_score + '积分奖励');
        if(type != 2){
            $(likeDoom).addClass('appraise-active');
            aftersale.removeAction(likeDoom,'appraise-active',3000);
        }
        aftersale.removeAction('#appraise-tip-box','appraise-tips-active',3000);

        //按钮点击统计
        if(type == 1){
            common.buttonClikcStatistics("appraise","appraise_like","产品点赞");
        }
    }});
}

/**
 * 询问是否要踩
 * @method aftersale.fruitDontLikeBtn
 * @param {String} pid 产品pid
 * @param {String} lid 产品lid
 * @param {Number} type 点赞类型
 */
aftersale.fruitDontLikeBtn = function(pid,lid,type){
    var param = pid + ',' + lid + ',' + type;
    tipsBox.createConfirmBox('你选择了‘不喜欢’，是否确定？','aftersale.fruitLikeBtn',param,'确定','取消');
}

/**
 * 产品取消点赞
 * @method aftersale.closeLike
  * @param {Number} id 产品id
 */
aftersale.closeLike = function(id){
    var order_id = $('#order_id').val();
    var url = api_host + "/Api/AfterSale/cancel_prais";
    var openid = user.userBase.bingo_openid;
    var data = {
        bingo_access_token: openid
        ,bingo_openid: openid
        ,order_id: order_id
        ,product_id: id
    };
    $.ajax({type:'post', url: url, data: data, dataType: 'json',success: function(result){
        if(result.status != 1) {
            tipsBox.createAlertBox(result.data);
            return false;
        }

        $("#like-btn-" + id).find("span").removeClass('current');
        $("#like-btn-" + id).find("p").text('我要点赞').css('color','');
        tipsBox.hideTipsBox();

    }});
}

/**
 * 定时移除动作
 * @method aftersale.removeAction
 * @param {String} id 元素名称
 * @param {String} actionClass 动作名称
 * @param {Number} second 秒
 */
aftersale.removeAction = function(id, actionClass, second) {
    setTimeout("aftersale.removeActionCalss('"+id+"','"+actionClass+"')",second);
}

/**
 * 称除动作样式
 * @method aftersale.removeActionCalss
 * @param {Number} id 元素名称
 * @param {String} actionClass 样式名称
 */
aftersale.removeActionCalss = function(id, actionClass) {
    $(id).removeClass(actionClass);
}

/**
 * 打开/关闭产品评价弹窗
 * @method aftersale.fruitCommentBtn
 * @param {String} id 产品id
 * @param {Number} status 状态，0为隐藏
 */
aftersale.fruitCommentBtn = function(id,status,lid) {
    if(status == 0) {
        $('#fruit-appraise-mask').html("").hide();
        base.recoverPenetration();     //恢复底层滚动
        return false;
    }
    //加载loading
    $('.valuation-loading-mark').show();
    $('.valuation-loading-box').show();

    //写入商品评价数据
    var allData = {};
    var data_type = [];
    $.each(aftersale.product.list, function(i){
        if(aftersale.product.list[i].is_yugou == 1 || aftersale.product.list[i].is_free == 1){
            data_type.push(aftersale.product.list[i].id);
        }else{
            data_type.push(aftersale.product.list[i].pid);
        }

    });

    var arr_num = $.inArray(id, data_type);
    allData.item = aftersale.product.list[arr_num];

    for(var i = 0,len = aftersale.product_valuation.length; i < len; i++){
        if(aftersale.product_valuation[i].id == id){   //在已修改的评价数组里存在该商品,修改
            var comment_mark = allData.item.comment_mark;
            var product_valuation = aftersale.product_valuation[i];
            comment_mark.anonymous = product_valuation.anonymous;
            comment_mark.comment = product_valuation.txt;
        }
    }

    common.renderTpl("#fruit-appraise-mask",'after_sale/fruit_comment',allData);
    $('#fruit-appraise-mask').show();
    tipsBox.tipsBoxCenter('.fruit-appraise-wrap');

    base.preventPenetration();    //防止滚动穿透
    //关闭loading
    $('.valuation-loading-mark').hide();
    $('.valuation-loading-box').hide();

    //按钮点击统计
    common.buttonClikcStatistics("appraise","appraise_submitValuation","产品评价");

    if($('#fruit-inner-' + id).find('i').text() == '去评价'){    //没有评价
        return false;
    }
    for(var i = 0,len = aftersale.product_valuation.length; i < len; i++){
        if(aftersale.product_valuation[i].id == id){   //在已修改的评价数组里存在该商品
            // $('#fruit-comment').val(aftersale.product_valuation[i].txt);     //写入评价
            var marks = aftersale.product_valuation[i].marks.split(",");
            $('.fruit-tags ul li').each(function() {       //写入标签
                if($.inArray($(this).data("id").toString(), marks) >= 0){
                    $(this).addClass('selected');
                }else{
                    $(this).removeClass('selected');
                }
            });
        }
    }
    $('#fruit-comment-submit').removeClass('bg');
}

/**
 * 选择评价标签
 * @mehotd appraise.fruitTagSelected
 * @param {Object} _this 对象
 * @param {String} tagid 标签id
 */
aftersale.fruitTagSelected = function(_this,tagid) {
    _this.toggleClass('selected');
    aftersale.allowCommentFruit();
}

/**
 * 允许用户评价水果
 * @method aftersale.allowCommentFruit
 */
aftersale.allowCommentFruit = function() {
    var sum = 0;
    $('.fruit-tags ul li').each(function() {
        if($(this).hasClass('selected')) {
            sum ++;
        }
    });
    var comment = $.trim($('#fruit-comment').val());
    if(comment != '' || sum > 0) {
        $('#fruit-comment-submit').removeClass('bg');
    } else {
        $('#fruit-comment-submit').addClass('bg');
    }
}

/**
 * 提交某个水果的评价
 * @method aftersale.submitValuation
 */
aftersale.submitValuation = function(){
    if($('#fruit-comment-submit').hasClass('bg')){
        //不能提交
        return false;
    }

    var thisComment = $("#fruit-comment").val();
    var product_id = $("#product-valuation-id").val();
    var order_id = $('#order_id').val();
    var marks = "";
    var comment_score = $("#comment_score").val();
    var lid = $('#product-valuation-lid').val();

    if($('#fruit-anonymous-btn').hasClass('current')){
        var anonymous = 1;
    }else{
        var anonymous = 0;
    }

    $(".fruit-tags ul li").each(function(){
        if($(this).hasClass('selected')) {
            if(marks == ""){
                marks += $(this).data("id");
            }else{
                marks += "," + $(this).data("id");
            }
        }
    });

    var url = api_host+"/Api/AfterSale/comment_product";
    var openid = user.userBase.bingo_openid;
    if (openid==undefined || openid==null || openid.length==0){
        return false;
    }
    var data={
        bingo_access_token: openid
        ,bingo_openid: openid
        ,order_id:order_id
        ,pid: product_id
        ,txt: thisComment
        ,marks: marks
        ,lid: lid
        ,anonymous: anonymous
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        if(result.status != 1) {
            tipsBox.createAlertBox(result.data);
            return false;
        }
        //写入商品评价数据
        var data_type = [];
        $.each(aftersale.product_valuation, function(i){
            data_type.push(aftersale.product_valuation[i].id);
        });

        var arr_num = $.inArray(product_id, data_type);
        if(arr_num >= 0){
            aftersale.product_valuation[arr_num].id = product_id;
            aftersale.product_valuation[arr_num].txt = thisComment;
            aftersale.product_valuation[arr_num].marks = marks;
            aftersale.product_valuation[arr_num].anonymous = anonymous;
        }else{
            aftersale.product_valuation.push({id:product_id, txt:thisComment, marks:marks, anonymous:anonymous});    //记录已修改的产品评价
        }
        if($("#comment-btn-" + product_id).find("span").hasClass('current')){    //已经有评价
            aftersale.fruitCommentBtn(0,0);
            return false;
        }
        if($('#fruit-inner-' + product_id).find('i').text() == '去评价'){
            $('#appraise-tip-box').text('感谢你的评价，获得' + comment_score + '积分奖励');
            $('#appraise-tip-box').addClass('appraise-tips-active');
            aftersale.removeAction('#appraise-tip-box','appraise-tips-active',3000);
        }
        $('#fruit-inner-' + product_id).find('i').text('已评价').css('background','#ccc');
        aftersale.fruitCommentBtn(0,0);
    }});
}

/**
 * 匿名评价按钮
 * @method aftersale.anonymousBtn
 */
aftersale.anonymousBtn = function(){
    if($('#fruit-anonymous-btn').data('lock') == 'lock'){
        //已锁定无法修改
        return false;
    }
    if($('#fruit-anonymous-btn').hasClass('current')){
        //关闭操作
        $('#fruit-anonymous-btn').removeClass('current');
        $('#fruit-anonymous-btn i').animate({left: 2},100);
    }else{
        //打开操作
        $('#fruit-anonymous-btn').addClass('current');
        $('#fruit-anonymous-btn i').animate({left: 19},100);
    }
}

/**
 * 展开或收起评价的商品列表/展开或收起已评价的快递员
 * @method aftersale.openOrdCloseList
 * @param {Number} type 0商品或1快递员
 */
aftersale.openOrdCloseList = function(type){
    if(type == 0){
        $(".appraise-main").toggle();
        $("#checkappraise_product i").toggleClass('icon-angle-up');
        $("#checkappraise_product i").toggleClass('icon-angle-down');
    }else{
        $("#appraise_deliveryman").toggle();
        $("#checkappraise_deliveryman i").toggleClass('icon-angle-up');
        $("#checkappraise_deliveryman i").toggleClass('icon-angle-down');
    }

}

/**
 * 获得"我有话说"输入框焦点
 */
aftersale.submitbtnStatus = function(){
    if($('#comment').text() != ""){
        $('#appraise-submitbtn').removeClass('btn-cancle-bg').addClass('style-color').text('提交评价');
    }
}

/**
 * 随机获得奖品
 * @method aftersale.get_red
 */
aftersale.get_red = function() {
    var html = template('aftersale_red',{});
    $("#app_content").html(html);
    common.loaded(0);
}

/**
 * 用户投诉快递员
 * @method aftersale.courier_complaint
 * @param {Number} oid 订单id
 */
aftersale.courier_complaint = function(oid) {
    var data = { oid : oid };
    common.renderTpl("#app_content",'after_sale/courier_complaint',data);
    common.loaded(0);
}

/**
 * 用户提交投诉快递员的原因
 * @method aftersale.complaint_delivweyman
 */
aftersale.complaint_deliveryman = function() {
    var oid = $('#oid').val();
    var reason = $('#reason').val();
    // var complainant = select_area.city_list[user.userBase.city_code] + user.userBase.short_name + user.userBase.nickname;
    var complainant = "用户ID：" + user.userBase.id;
        complainant += "；<br>用户城市：" + select_area.city_list[user.userBase.city_code];
        complainant += "；<br>地区：" + user.userBase.short_name;
        complainant += "；<br>订单ID：" + oid;
        complainant += "；<br>用户名称：" + user.userBase.nickname;
        complainant += "；<br>用户投诉内容：" + reason;
    if(reason == '') {
        tipsBox.createAlertBox('请输入您投诉原因');
        return false;
    }
    var url = api_host+"/Api/AfterSale/complaint_deliveryman";
    var openid = user.userBase.bingo_openid;
    if (openid==undefined || openid==null || openid.length==0){
        return false;
    }
    var data={
        bingo_access_token:openid
        ,bingo_openid:openid
        ,order_id:oid
        ,reason:reason
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
       if(result.status == 1) {
            aftersale.complaint_email("用户投诉",complainant);
            window.location.href = '#/complaint_success';
       } else {
            tipsBox.createAlertBox(result.data);
       }
    }});
}

aftersale.complaint_email = function(title,content) {
     var url = api_host+"/Api/Email/sendEmail";
     var data = { type : 'HTML',subject : title,content : content };
     $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){}});
}


/**
 * 用户投诉成功
 * @method aftersale.complaint_success
 * @returns {boolean}
 */
aftersale.complaint_success = function() {
    var url = api_host + "/Api/league/get_user_league";
    var openid = user.userBase.bingo_openid;
    var data = { bingo_access_token: openid ,bingo_openid: openid };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        common.renderTpl("#app_content",'after_sale/complaint_success',result);
        common.loaded(1);
    }});
}

/**
 * 感谢用户评价
 * @param {String} orderno 订单号
 * @param {Number} status 状态
 */
aftersale.aftersale_thank = function(orderno, status) {
    common.renderTpl("#app_content",'after_sale/thank',{});
    common.loaded(1);
    if(status != 1) {
        $('#fixed-tips').html('你的评价已修改成功');
        tipsBox.createAlertBox('你的评价已修改成功');
    }
}

aftersale.appraise_fruit = function() {
    var order_no = $('#order_no').val();
    window.location.href = '#/thank/'+order_no+'/'+2;
}

/**
 * 提交评价快递员
 * @method aftersale.appraise_deliveryman
 */
aftersale.appraise_deliveryman = function() {
    if($('#appraise-submitbtn').hasClass('btn-cancle-bg')){
        return false;
    }
    var send_type = $('#send_type').val();
    if(send_type == 1 || send_type == 3) {
        var speed = $(window.frames["iframeName"].document).find('input[name="speed"]:checked').val();
        var service = $(window.frames["iframeName"].document).find('input[name="service"]:checked').val();
    } else {
        var speed = 3;
        var service = 3;
    }
    var order_id = $('#order_id').val();
    var order_no = $('#order_no').val();
    var comment = $('#comment').val();
    var appraise_status = $('#appraise_status').val();
    var url = api_host+"/Api/AfterSale/appraise_deliveryman";
    var openid = user.userBase.bingo_openid;
    if (openid == undefined || openid == null || openid.length == 0){
        return false;
    }
    var data = {
        bingo_access_token:openid,
        bingo_openid:openid,
        order_id:order_id,
        service:service,
        speed:speed,
        bingo_appid:config.appid ,
        comment:comment
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        if(result.status != 1) {
            tipsBox.createAlertBox(result.data);
            return false;
        }

        //按钮点击统计
        common.buttonClikcStatistics("appraise","appraise_deliveryman","送货员评价");

        window.location.href = '#/thank/'+order_no+'/'+appraise_status;
    }});
}

aftersale.update_feedback_status = function(return_id,return_name) {
    var url = api_host+"/Api/AfterSale/update_return_status";
    var openid = user.userBase.bingo_openid;
    var data={ bingo_access_token:openid ,bingo_openid:openid,return_id:return_id,status:-2 };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        if(result.status == 1) {
            if(result.data.status == 1) {
                tipsBox.createAlertBox('取消'+return_name+'成功');
                $('.feedback-method-inner div table tr td a').addClass('forbidden');
            } else {
                tipsBox.createAlertBox(result.data.txt);
            }
        } else {
            tipsBox.createAlertBox(result.data);
        }
    }});
}

aftersale.fresh_sorry_btn = function(method) {
    $('.indemnity-wrap label.radio-btn').removeClass('radio-current');
    $('#fresh_sorry_outline_0'+parseInt(method)).addClass('radio-current');

    var way =  $('input[name="way"]:checked').val();
    aftersale.fresh_sorry(way,method);
}

/**
 * 鲜赔理退货/换货提示
 * @method aftersale.fresh_sorry
 * @param {String} way
 * @param {Number}  method
 */
aftersale.fresh_sorry = function(way, method) {
   var ulStr = '';
   var titleStr = '';
   switch(parseInt(way)) {
       case 0:
           if(method == 0) {
                var undo_time = $('#undo_time').val();
                titleStr = '<h3>你选择了 <span style="color: #6fbfd9;">"鲜赔理"</span> 退货</h3>';
                ulStr += '<ul>';
                ulStr +=     '<li><em></em>缤果会先把退款金额打到你的账户,但该笔金额暂时处于<span>冻结状态</span></li>';
                ulStr +=     '<li><em></em>退货申请受理完成时,被冻结的金额将会解冻,你可以自由使用</li>';
                ulStr +=     '<li><em></em>若退货申请超过<span>'+undo_time+'小时</span>未处理,则冻结金额将自动解冻.</li>';
                ulStr += '</ul>';
            } else {
                titleStr = '<h3>你选择了 原路退回</h3>';
                ulStr = '<ul><li><em></em>缤果会在最短时间，将退款金额原路退回。</li></ul>';
            }
           break;
       case 1:
           if(method == 0) {
                var undo_time = $('#undo_time').val();
                titleStr = '<h3>你选择了 <span style="color: #6fbfd9;">"鲜赔理"</span> 换货</h3>';
                ulStr += '<ul>';
                ulStr +=     '<li><em></em>缤果会先行赔付换货金额,将其打入你的账户,但该笔金额暂时处于<span>冻结状态</span>.</li>';
                ulStr +=     '<li><em></em>当换货完成时,先行赔付的冻结金额将被收回.</li>';
                ulStr +=     '<li><em></em>若换货超过<span>'+undo_time+'小时</span>未处理,被冻结的金额将自动解冻,并且缤果不会取回换货商品</li>';
                ulStr += '</ul>';
            } else {
                titleStr = '<h3>你选择了 普通换货</h3>';
                ulStr = '<ul><li><em></em>缤果会在最短时间内,上门更换商品.</li></ul>';
            }
           break;
   }
   var html = '<div class="alert-wrap">'+titleStr+ulStr+'<p><a href="javascript:void(0);" onclick="tipsBox.hideTipsBox()">知道了</a></p></div>';
   $(tipsBox.container).html(html);
   $(tipsBox.container).show();
   tipsBox.tipsBoxCenter(tipsBox.container + ' > div.alert-wrap');
}

aftersale.returnFormula = function(num) { //计算优惠
    var price = parseFloat($('#product_price').val());
    var sale_price = parseFloat($('#sale_price').val());
    var sum_price = parseFloat($('#sum_price').val())
    var product_is_free = parseInt($('#product_is_free').val());
    var sp_sum_price = parseFloat($('#sp_sum_price').val());
    var return_price = 0;
    var sum  = price * num;
    sum = sum == parseInt(sum) ? parseInt(sum) : sum.toFixed(2);
    if(product_is_free == 1) {
        return_price = sum;
    } else {
        return_price = sum - ((sum / (sum_price - sp_sum_price)) * sale_price);
    }
    // return_price = return_price == parseInt(return_price) ? parseInt(return_price) : return_price.toFixed(1)+"0";
    return_price = return_price > 0 ? return_price : 0;
    return_price = base.setNumberDecimals(return_price);
    $('#return_price').html(return_price);
}


aftersale.apply_return_btn_sure = function() {
    tipsBox.hideTipsBox();
    $('#submit_status').val(1);
    aftersale.apply_return_btn();
}

aftersale.apply_return_btn = function() {
    if(aftersale.apply_return_btn_status == 0) {
        return false;
    }
    var url = api_host+"/Api/AfterSale/apply_return";
    var openid = user.userBase.bingo_openid;
    if (openid==undefined || openid==null || openid.length==0){
        return false;
    }

    var order_id = $('#order_id').val();
    var product_id = $('#product_id').val();
    var num = parseInt($('#product_num').val());
    var way =  $('input[name="way"]:checked').val();
    var why =  $('input[name="why"]:checked').val();
    var fresh_sorry = $('input[name="fresh_sorry"]:checked').val();
    var submit_status = $('#submit_status').val();
    var productWeight = $('#productWeight').val();
    var productPrice = $('#product_price').val();

    var copy = $('#copy').val();
    var img_url = '';
    //var img_url = $('#imgUrl').val();
    var say = $('#say').val();
    if(way == undefined) {
        $('#submit_status').val(0);
        aftersale.apply_return_btn_status = 1;
        tipsBox.createAlertBox('请选择你希望退货/换货方式');
        return false;
    }

    if( parseInt(copy) < 1 ) {
        $('#submit_status').val(0);
        aftersale.apply_return_btn_status = 1;
        tipsBox.createAlertBox('请输入您想退货/换货的份数');
        return false;
    }

    if(parseInt(copy)  > num) {
        $('#submit_status').val(0);
        aftersale.apply_return_btn_status = 1;
        tipsBox.createAlertBox('退货/换货的份数最多只能退'+num+'份');
        return false;
    }

    if(fresh_sorry == undefined) {
        $('#submit_status').val(0);
        aftersale.apply_return_btn_status = 1;
        tipsBox.createAlertBox('请选择你的退款方式');
        return false;
    }

    if(why == undefined) {
        $('#submit_status').val(0);
        aftersale.apply_return_btn_status = 1;
        tipsBox.createAlertBox('请选择你希望退货/换货原因');
        return false;
    }

    if(submit_status == 0) {
        aftersale.apply_return_btn_status = 1;
        var tips = '退换货申请提交后,<span style="color:#F00">无法取消申请</span>是否继续提交?';
        tipsBox.createConfirmBox(tips,'aftersale.apply_return_btn_sure','','继续提交');
        return false;
    }

    aftersale.apply_return_btn_status = 0;
    $(".share-img-box li").each(function(index){
        if(!$(this).hasClass('add')){
            img_url += $(this).find('img').attr('src').replace('../Public/Uploads','')+",";
        }
    });

    var data={
        bingo_access_token:openid
        ,bingo_openid:openid
        ,order_id:order_id
        ,product_id:product_id
        ,why:why
        ,way:way
        ,copy:copy
        ,img_url:img_url
        ,say:say
        ,fresh_sorry:fresh_sorry
        ,price: productPrice      //产品价格
        ,weight: productWeight     //称重产品重量
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        aftersale.apply_return_btn_status = 1;
        if(result.status == 1) {
            productWeight = productWeight == "" ? 0 : productWeight;
            window.location.href ='#/feedback/' + order_id + '/' + product_id + '/' + productWeight;
        } else {
            $('#submit_status').val(0);
            tipsBox.createAlertBox(result.data);
        }
    }});
}

/**
 * 取消订单确订框
 * @method aftersale.cancelcomplaintBtn
 * @param {Number} oid 订单id
 */
aftersale.cancelcomplaintBtn = function(oid) {
    tipsBox.createConfirmBox('是否要撤销对本单的投诉，撤销后无法再次投诉。','aftersale.cancelComplaintOpera',oid,'马上撤销','考虑一下');
}

/**
 * 执行取消订单操作
 * @method aftersale.cancelComplaintOpera
 * @param {String} oid 订单id
 */
aftersale.cancelComplaintOpera = function(oid) {
    tipsBox.hideTipsBox();
    var url = api_host + "/Api/AfterSale/cancel_complaint_deliveryman";
    var openid = user.userBase.bingo_openid;
    var data= { bingo_access_token: openid, bingo_openid: openid, bingo_appid: config.appid , order_id: oid };
    $.ajax({type: 'post', url: url, data: data, dataType: 'json', success: function(result) {
        if (result.status == 1) {
            $('#complainting-box').hide();
            $('#cancel-complainting-box').show();

            $('.appraise-complaint div:first-child').hide();
            $('.appraise-complaint div:last-child').show();
            tipsBox.hideTipsBox();
        } else {
            tipsBox.createAlertBox(result.data);
        }
    }});
}

/**
 * 退货换货列表
 * @method aftersale.return_exchange
 * @param {Number} orderno 订单号
 * @param {Number} type 类型，控制返回页面路径
 */
aftersale.return_exchange = function(orderno, type) {
    var url = api_host + "/Api/AfterSale/get_appraise_info";
    var openid = user.userBase.bingo_openid;
    var data = { bingo_access_token: openid, bingo_openid: openid, orderno: orderno };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        var returnUrl = (type == 0) ? '#/order/receive' : 'javascript:history.back()';
        common.renderTpl("#app_content",'after_sale/return_exchange',result);
        common.loaded(1);
        $('#back-btn').attr('href',returnUrl);
    }});
}

/**
 * 订单申请退换货
 * @method aftersale.return_goods
 * @param {Number} order_id 订单id
 * @param {Number} product_id 产品id
 * @param {Number} price 产品价格
 * @param {String} weights 称重产品重量
 * @returns {boolean}
 */
aftersale.return_goods = function(order_id, product_id, price, weights) {
    var weight = weights == 0 ? "" : weights;
    var url = api_host + "/Api/AfterSale/get_return_product";
    var openid = user.userBase.bingo_openid;
    var data = {
        bingo_access_token: openid
        ,bingo_openid: openid
        ,order_id: order_id
        ,product_id: product_id
        ,price: price
        ,weight: weight
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        $('#file-input').val('');
        uploadImg.upComplete = 1;
        uploadImg.folder = 'Article';
        result.data.order_id = order_id;
        result.data.product_id = product_id;

        common.renderTpl("#app_content",'after_sale/return_goods',result.data);
        common.loaded(1);
        if(result.data.allow_return != 1 || result.data.is_return == 1) {
            var tips = '你的退货/换货申请超过'+result.data.allow_return_time+'小时，不能再申请了，如需帮助，请联系客服。';
            if(result.data.is_return == 1) {
                tips = '你已经申请过了';
            }
            navigation.commonFooterTpl('提交','','tipsBox.createAlertBox("'+tips+'")');
            $('#footer a').attr('style','background:#999');
        } else {
            navigation.commonFooterTpl('提交','','aftersale.apply_return_btn()');
        }
    }});
}

/**
 * 退货换货加操作
 * @method aftersale.plus_btn
 */
aftersale.plus_btn = function() {
    var copy = parseInt($('#copy').val()) + 1;
    var num = parseInt($('#product_num').val());
    $('#subtract_btn').removeClass('forbidden');
    if(copy >= num) {
        copy = num;
        $('#plus_btn').addClass('forbidden');
    } else {
        $('#plus_btn').removeClass('forbidden');
    }
    $('#copy').val(copy);
    $('#return-way-num').html(copy);
    aftersale.returnFormula(copy);
}

/**
 * 退货换货减操作
 * @method aftersale.plus_btn
 */
aftersale.subtract_btn = function() {
    var copy = parseInt($('#copy').val()) - 1;
    var num = parseInt($('#product_num').val());
    $('#plus_btn').removeClass('forbidden');
    if(copy <= 1 ) {
        copy = 1;
        $('#subtract_btn').addClass('forbidden');
    } else {
        $('#subtract_btn').removeClass('forbidden');
    }
    $('#copy').val(copy);
    $('#return-way-num').html(copy);
    aftersale.returnFormula(copy);
}

/**
 * 查看退款详情按钮
 * @method aftersale.show_save_info
 */
aftersale.show_save_info = function() {
    var return_price = $('#return_price').html();
    var tips = '由于你的订单使用了优惠，退还的金额会按一定的比例折算，退还金额为'+return_price+'元<div class="retrun-save-tips"><span class="border border-left">&nbsp;</span><span class="return-price ng-binding style-color">应退: '+return_price+'元</span><span class="border border-right">&nbsp;</span></div>';
    tipsBox.createAlertBox(tips);
}

/**
 * 选择退货理由
 * @method aftersale.select_why_btn
 * @param id
 */
aftersale.select_why_btn = function(id) {
    $('.return-select-inner ul li label').removeClass('radio-current');
    $('#why_'+id).parent().find('label.radio-btn').addClass('radio-current');
}

/**
 * 用户选择退货/换货
 * @param model
 */
aftersale.return_way_btn = function(model) {
    var name = (model == 0) ? '退': '换';
    var num = parseInt($('#product_num').val())  > 1  ?parseInt($('#product_num').val()) : 0;
    var copy = parseInt($('#copy').val());
    $('.return-way-hope label.radio-btn').removeClass('radio-current');
    $('#way_label_0'+parseInt(model)).addClass('radio-current');

    $('#return-way-name').html(name);
    if(num > 1) {
        $('#return-hope-num-box').show();
    }
    if(copy <= 1) {
        $('#subtract_btn').addClass('forbidden');
    }

    $('.indemnity-wrap label.radio-btn').removeClass('radio-current');
    var x = document.getElementsByName("fresh_sorry");
    for(var i = 0; i < x.length; i++){
        if(x[i].checked == true) {
            x[i].checked = false;
        }
    }

    $('.indemnity-wrap').show();
    var is_ready_money = $('#is_ready_money').val();
    if(model == 0) {
        $('.return-price-box').show();
        $('.fresh-sorry-tips-01').show();
        $('.fresh-sorry-tips-02').hide();
        if(parseInt(is_ready_money) === 1) {
            $('#fresh-model-01').removeClass('add-bottom');
            $('#fresh-model-02').hide();
        } else {
            $('#fresh-model-01').addClass('add-bottom');
            $('#fresh-model-02').show();
        }
        aftersale.returnFormula(copy);
    } else {
        $('.return-price-box').hide();
        $('.fresh-sorry-tips-01').hide();
        $('.fresh-sorry-tips-02').show();
        $('#fresh-model-01').addClass('add-bottom');
        $('#fresh-model-02').show();
    }
}

/**
 * 订单退货换货跟踪
 * @method aftersale.feedback
 * @param {Number} order_id 订单id
 * @param {Number} product_id 产品id
 * @param {String} weight 称重产品重量
 */
aftersale.feedback = function(order_id, product_id, weight) {
    var weight = weight == 0 ? "" : weight;
    var url = api_host + "/Api/AfterSale/get_return_status";
    var openid = user.userBase.bingo_openid;
    var data = {
        bingo_access_token: openid
        ,bingo_openid: openid
        ,order_id: order_id
        ,product_id: product_id
        ,weight: weight
    };
    $.ajax({type: 'post', url: url, data: data, dataType: 'json', success: function(result){
        result.data.return_name = (result.data.return_way == 0) ? '退货' : '换货';
        common.renderTpl("#app_content",'after_sale/feedback',result.data);
        common.loaded(0);

        if(result.data.return_status !== '0') {
            if(parseInt(result.data.return_status) > 0) {
                $('.feedback－tracking-inner ul li:first-child').addClass('current');
            } else {
                $('.feedback－tracking-inner ul li:first-child').addClass('fail');
            }
            if(result.data.return_status === '-3' && result.data.return_note != '') {
                $('.feedback-inner div.apply-error').show();
            }
        }

        if(result.data.return_shop_hours == 0 && result.data.return_status == 0) {
            tipsBox.createAlertBox('你的'+result.data.return_name+'申请已收到了，不过店长已经下班拉~会在明天及时处理你的申请哦!');
        }
    }});
}
//重构alert框
var alertBox = function(_this,_tips){
    $(_this).show();
    $(_this + ' h3').html(_tips);
    tipsBoxCenter(_this + ' div');
}
var alertBoxHide = function() {
    $('.alert-box').hide();
}

//提示框上下居中
var tipsBoxCenter = function(_this) {
    var windowHeight = $(window).height();
    var _thisHeight = $(_this).css('height').replace('px','');
    var top = parseFloat(windowHeight - _thisHeight) / 2;
    $(_this).css('marginTop',top);
}

var tipsBox = {}
tipsBox.container = '#tips-box';
tipsBox.dynamicFunction = function(name,param) { //动态生成函数
    var paramArr = param.split(",");
    var paramStr = "";
    for(var key in paramArr){
        paramStr += '\"' + paramArr[key] + '\",';
    }
    paramStr = paramStr.substring(0,paramStr.length - 1);
    return Function('return ' + name + '(' + paramStr + ')')();
}

tipsBox.createAlertBox = function(tips) { //生成alert提示框
    var html = '<div class="alert-wrap"><h3>'+tips+'</h3><p><a href="javascript:void(0);" onclick="tipsBox.hideTipsBox()">知道了</a></p></div>';
    $(tipsBox.container).html(html);
    $(tipsBox.container).show();
    tipsBox.tipsBoxCenter(tipsBox.container + ' > div.alert-wrap');
}

tipsBox.createAlertBoxAll = function(tips,sure,url,align) { //生成alert提示框
    var sure  = (sure != undefined && sure != '' ) ? sure: '知道了';
    var url = (url != undefined && url != '' ) ? url: 'javascript:void(0)';
    var align  = (align != undefined && align != '') ? align: 'tl';

    var html = '<div class="alert-wrap"><h3 class="'+align+'">'+tips+'</h3><p><a href="'+url+'" onclick="tipsBox.hideTipsBox()">'+sure+'</a></p></div>';
    $(tipsBox.container).html(html);
    $(tipsBox.container).show();
    tipsBox.tipsBoxCenter(tipsBox.container + ' > div.alert-wrap');
}

tipsBox.createConfirmBox = function(tips, name, param, sure, cancel) { //生成同意提示框
    var sure  = (sure != undefined ) ? sure: '同意';
    var cancel  = (cancel != undefined ) ? cancel: '取消';
    var html = '<div class="confirm-wrap"><h3 >'+tips+'</h3><table border-collapse="0" border-spacing="0"><tr><td><a href="javascript:void(0);" onclick="tipsBox.hideTipsBox()">'+cancel+'</a></td><td><a href="javascript:void(0);" onclick="tipsBox.dynamicFunction(\''+name+'\',\''+param+'\')">'+sure+'</a></td></tr></tabel></div></div>';
    $(tipsBox.container).html(html);
    $(tipsBox.container).show();
    tipsBox.tipsBoxCenter(tipsBox.container + ' > div.confirm-wrap');
}

tipsBox.hideTipsBox = function() { //关闭提提示框
    $(tipsBox.container).removeAttr('style');
}

tipsBox.tipsBoxCenter = function(_this) { //提示框居中
    var windowHeight = $(window).height();
    var _thisHeight = $(_this).css('height').replace('px','');
    var top = parseFloat(windowHeight - _thisHeight) / 2;
    $(_this).css('marginTop',top);
}

tipsBox.createShareBox = function(imgurl) { //分享图片
    var html = '<img src="'+imgurl+'" width="100%" onclick="tipsBox.hideTipsBox()"/>';
    $(tipsBox.container).html(html);
    $(tipsBox.container).show();
}

tipsBox.createShareAppBox = function() {//app分享
    common.renderTpl(tipsBox.container,'share/share_app',{});
    $(tipsBox.container).css('background','rgba(0,0,0,0.75)');
    $(tipsBox.container).show();
    var height = $('.share-app-box li').width() - 1;
    var dd = $('.share-app-box dd').height();
    var dt = height * 0.4;

    $('.share-app-box li').css('height',height);
    $('.share-app-box dl').css('paddingTop', parseInt( (height - dt - dd  ) / 2 ) );
}

tipsBox.AppUpload = function() { //缤果App升级
    var sure  = '升级';
    var cancel  = '关闭';
    var tips = '检查到有新的版本，是否升级？';
    var html = '<div class="confirm-wrap"><h3 >'+tips+'</h3><table border-collapse="0" border-spacing="0"><tr><td><a href="javascript:void(0);" onclick="tipsBox.hideTipsBox()">'+cancel+'</a></td><td><a href="itms-apps://itunes.apple.com/app/id935174431">'+sure+'</a></td></tr></tabel></div></div>';
    $(tipsBox.container).html(html);
    $(tipsBox.container).show();
    tipsBox.tipsBoxCenter(tipsBox.container + ' > div.confirm-wrap');
    return false;
}

tipsBox.logistics = function(id,tracking_number) { //物流信息
    var data = {
        'name': order_list.tracking[id],
        'number': (tracking_number != '') ? tracking_number : '快递员正在取件中'
    }
    common.renderTpl(tipsBox.container,'./alert/logistics',data);
    $(tipsBox.container).show();
    tipsBox.tipsBoxCenter(tipsBox.container + ' > div.logistics-wrap');
    return false;
}
/**
 * base 基础功能
 */
var base = {};
base.bodyscrollTop = 0;     //记录滚动条位置
/**
 * 数字如果是正数,格式化成正数,不是正数，保留数字
 * @method base.setNumberIntegral
 * @param {Number} number 数字
 * @param {Number} decimal 保留小数点,默认是2位小数
 * @return {Number}
 */
base.setNumberIntegral = function(number, decimal) {
    decimal = (decimal != undefined) ? decimal : 2;
    if(number > parseInt(number)){
        return number = number.toFixed(decimal);
    }
    return parseInt(number);
}

/**
 * 不四舍五入保留所需要的小数位数,如果是小数位都是0，格式化为正整数
 * @method base.setNumberDecimals
 * @param {Number} number 需要格式化的数字
 * @param {Number} decimal 保留小数位，10是一位，100是两位，默认是一位小数
 * @return {Number}
 */
base.setNumberDecimals = function(number,decimal){
    decimal = (decimal != undefined) ? decimal : 10;
    number = (number != undefined && number != null && number != '') ? number : 0;
    if(number > parseInt(number)){
        return Math.floor(number * decimal) / decimal;
    }
    return parseInt(number);
}

/**
 * 数字的加法减法运算(精确)
 * @method base.numberMathOperations
 * @param {Number} numberl 左边运算数
 * @param {Number} numberr 右边运算数
 * @param {Number} type 类型 1加法/2减法
 * @return {Number}
 */
base.numberMathOperations = function(numberl, numberr, type){
    var result = 0;
    var numberLeft = numberl * 100;
    var numberRight = numberr * 100;
    switch(parseInt(type)){
        case 1:
            //加法
            result = numberLeft + numberRight;
            break;
        case 2:
            //减法
            result = numberLeft - numberRight;
            break;
    }
    // result = base.setNumberDecimals(result/100);
    result = result/100;
    return result;
}

/**
 * 替换存在的字符
 * @method base.replaceString
 * @param {String} string 字符串
 * @param {String} regexp 需要替换的字符
 * @param {String} replacement 替换后的字符
 * @return {String}
 */
base.replaceString = function(string, regexp, replacement) {
    if(string.indexOf(regexp) == -1) {
        return string;
    }
    return string.replace(regexp,replacement);
}

/**
 * 防止弹出层的滚动穿透到底层
 * @method base.preventPenetration
 */
base.preventPenetration = function(){
    if(config.isAppleDevice == 1){      //ios
        $('#app_content').css('overflow','hidden');
        return false;
    }
    base.bodyscrollTop = $(window).scrollTop();
    $('html,body').addClass('penetration-in');
}

/**
 * 恢复底层滚动，与base.preventPenetration配合使用
 * @method base.recoverPenetration
 */
base.recoverPenetration = function(){
    if(config.isAppleDevice == 1){      //ios
        $('#app_content').css('overflow','');
        return false;
    }
    $('html,body').removeClass('penetration-in');
    $(window).scrollTop(base.bodyscrollTop);
    base.bodyscrollTop = 0;
}

/**
 * 防止重复提交，检查按钮状态是否锁定
 * @method base.checkBtnLock
 * @return {Boolean}
 */
base.checkBtnLock = function(){
    if($("body").data("applycancel") == "lock"){
        return false;
    }else{
        $("body").data("applycancel","lock");
        return true;
    }
}

/**
 * 解除按钮锁定
 * @method base.clearBtnLock
 * @return {Boolean}
 */
base.clearBtnLock = function(){
    $("body").data("applycancel","unlock");
}

/**
 * 传入数字返回星期名称，1代表星期一/周一，0代表星期天/周日、
 * @method base.numberWeek
 * @param {Number} number 代表星期的数字
 * @param {String} type 类型，0是周一，1是星期一
 */
base.numberWeek = function(number,type){
    if(type == undefined){
        type = 0;
    }
    number = (number == 7) ? 0 : number;  //兼容数字7
    var weekList0 = ['周日','周一','周二','周三','周四','周五','周六'];
    var weekList1 = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'];
    var week = '';
    if(type == 0){
        week = weekList0[parseInt(number)];
    }else if(type == 1){
        week = weekList1[parseInt(number)];
    }else{
        week = "未知";
    }
    return week;
}

/**
 * 获取某星期的日期(年/月/日)
 * @method base.nextWeekDate
 * @param {Number} weeknumber 星期几，1代表星期一，0代表星期日
 * @param {Number} rate 倍率,0为本周，1为下周，2为下下周，3为下下下周，依次类推
 * @return {Object} date
 */
base.nextWeekDate = function(weeknumber,rate){
    weeknumber = (weeknumber == 7) ? 0 : weeknumber;   //兼容数字7
    rate = (rate == undefined) ? 1 : rate;      //默认为下周
    var date = new Date(); // 获取当前时间
    var day = date.getDay(); // 获取今天是星期几
    var offset = Number(weeknumber) - day; // 计算出差几天

    // offset = offset <= 0 ? offset + offsetDay : offset;
    offset = offset + 7 * rate;     //变成以后的周

    date = date.getTime(); // 拿到当前的时间戳
    var nextWeek = date + offset * 24 * 3600 * 1000; // 计算出时间戳

    nextWeek = new Date(nextWeek); // 转成时间对象

    var nextWeekYear = nextWeek.getFullYear();    //获取年份
    var nextWeekMonth = nextWeek.getMonth() + 1; // 获取月份
    var nextWeekDay  = nextWeek.getDate();      // 获取日期

    // nextWeekDay = nextWeekDay < 10 ? '0' + futureDate : nextWeekDay.toString(); // 如果日期小于10则补个0

    return date = {year: nextWeekYear, month: nextWeekMonth,day: nextWeekDay};
    // return date = nextWeekMonth + '月' + nextWeekDay + '号';
}

/**
 * 计算两个日期相差的天数，格式：YYYY-MM-DD
 * @method base.daysBetween
 * @param {String} DateOne 第一个日期
 * @param {String} DateTwo 第二个日期
 * @return {Number}
 */
base.daysBetween = function(DateOne,DateTwo) {
    var OneMonth = DateOne.substring(5,DateOne.lastIndexOf ('-'));
    var OneDay = DateOne.substring(DateOne.length,DateOne.lastIndexOf ('-')+1);
    var OneYear = DateOne.substring(0,DateOne.indexOf ('-'));

    var TwoMonth = DateTwo.substring(5,DateTwo.lastIndexOf ('-'));
    var TwoDay = DateTwo.substring(DateTwo.length,DateTwo.lastIndexOf ('-')+1);
    var TwoYear = DateTwo.substring(0,DateTwo.indexOf ('-'));

    var cha=((Date.parse(OneMonth+'/'+OneDay+'/'+OneYear)- Date.parse(TwoMonth+'/'+TwoDay+'/'+TwoYear))/86400000);
    return Math.abs(cha);
}

/**
 * 字符串时间转为时间戳
 * @method base.getUnixTime
 * @param {String} dateStr 格式 2016-7-18 11:0:0
 */
base.getUnixTime = function(dateStr){
    var newstr = dateStr.replace(/-/g,'/');
    var date =  new Date(newstr);
    var time_str = date.getTime().toString();
    return time_str.substr(0, 10);
}

/**
 * 值是否在数组里
 * @method base.inArray
 * @param {Array} arr 数组
 * @param {String} val 值
 * @returns {boolean}
 */
base.inArray = function(arr, val) {
    for(var i in arr){
        if(arr[i] == val){
            return true;
        }
    }
    return false;
}

/**
 * 对象数组化
 * @method base.resetArr
 * @param {Object} Object 对象
 * @param {String} key 关键字
 */
base.resetArr = function(object, key) {
    var arr = [];
    var key = key || 'id';
    var object = object || '';

    if(object == '') {
        return arr;
    }

    for(var i in object) {
        arr[object[i][key]] = object[i];
    }

    return arr;
}
/**
 * 订悦功能
 */
var booking = {};
booking.packageData = null;     //所有订悦套餐数据
booking.selectPackage = null;    //选择的套餐
booking.bookingNav = [];      //订悦导航数据
booking.navClass = "";       //选择的类型
booking.bookingFrequency = 0;   //频次
booking.bookingFrequencyName = '';    //频次名称
booking.bookingPeopleNum = 0;    //人数
booking.bookingTime = 0;     //周期
booking.bookingTimePrice = 0;    //周期价格
booking.deliveryDay = "";    //配送日期
booking.bookingAddress = null;   //配送联动地址
booking.nodeId = -1;     //配送区域ID
booking.sendType = 1;    //配送方式
booking.deliveryFee = 0;      //配送一次的运费
booking.renewalStatus = 0;    //是否是续订，0否/1是
booking.sendTimeRate = 1;    //配送日期倍率，1是下周，2是下下周
booking.firstWeekTime = "";    //第一次配送的时间

/**
 * 订悦产品入口
 * @method booking.entrance
 * @param {String} type 订悦类型
 */
booking.entrance = function(type){
	if(booking.packageData == null){
		var url = api_host + '/Api/Subscription/subscription_list';
		var openid = user.userBase.bingo_openid;
		if (openid == undefined || openid == null || openid.length == 0){
		    return false;
		}
		var data = {
			bingo_access_token: openid
			,bingo_openid: openid
			,app_id: config.appid
		}
		$.ajax({type: 'post', url: url, data: data, dataType: 'json', success:function(result){
			// return false;
			booking.packageData = result.data;

			if(result.data.length == 0){
				common.noFoundResult('没有商品哦～','#app_content');
				common.loaded(0);
				return false;
			}
			//设置导航数据
			for(var i = 0,len = result.data.length; i < len; i++){
				booking.bookingNav.push({className: result.data[i].class_name,classMark: result.data[i].class_mark});
			}

		    //设置切换菜单和数据
		    booking.menu(type);
		}});
	}else{
		//设置切换菜单和数据
		booking.menu(type);
	}
}

/**
 * 设置订悦产品切换菜单，切换时保存新的套餐数据booking.selectPackage
 * @param {String} type 订购类型
 * @method booking.menu
 */
booking.menu = function(type){
	//默认选中水果
	// booking.navClass = type;
	booking.renewalStatus = 0;    //重置续订状态
	var data = booking.packageData;
	for(var i = 0,len = data.length; i < len; i++){
		if(data[i].class_mark == type){
			booking.selectPackage = data[i];
		}
	}
	if(booking.selectPackage == null){
		booking.selectPackage = data[0];
	}
	booking.navClass = booking.selectPackage.class_mark;

	booking.productShow();
	common.loaded(0);

}

/**
 * 订悦产品数据显示
 * @method booking.productShow
 */
booking.productShow = function(){

	var data = booking.selectPackage;
	common.renderTpl("#app_content",'booking/booking',data);
	if(data.class_mark === undefined){
		common.noFoundResult('没有商品哦～','#view_page');
		return false;
	}
	$('#producInfoContent').html(data.content);
	$('#producInfoContent img').css('width','100%');

    //设置底部按钮
    if(data.continue == 1){       //优先判断续订
    	booking.renewalStatus = 1;
		navigation.commonFooterTpl("我要续订", "#/booking_cart","");
    }else{
    	if(data.user_is_buy == 1){    //已购买过并且未配送完毕
    		navigation.commonFooterTpl("已预定", "","booking.uncanGoCart(1)");
    		$('#footer a').css('background','#ccc');
    	}
    	if(data.user_is_buy == 0 && data.user_is_full == 1){
    		navigation.commonFooterTpl("暂停接单", "","booking.uncanGoCart(2)");
    		$('#footer a').css('background','#ccc');
    	}
    	if(data.user_is_buy == 0 && data.user_is_full == 0){
    		navigation.commonFooterTpl("立即预定", "#/booking_cart","");
    	}
    }
    $('body').scrollTop(0);
}

/**
 * 前往订悦购物车
 * @method booking.cart
 * @param {String} type 订购类型
 */
booking.cart = function(type){
	//如果套餐数据是空的就跳转回产订悦首页
	if(booking.selectPackage == null){
		window.location.href = "#/booking";
		return false;
	}
	if(booking.renewalStatus == 1){   //续订保存nodeid
		var url = api_host + "/Api/Subscription/subscription_address_list";
		var openid = user.userBase.bingo_openid;
		if (openid == undefined || openid == null || openid.length == 0){
		    return false;
		}
		var data = {
			bingo_access_token: openid
			,bingo_openid: openid
		};
		$.ajax({type: 'post', url: url, data: data, dataType: 'json', success: function (result) {

			booking.bookingAddress = result.data;

			var bookingCity = booking.selectPackage.pre_addr.city;
			var bookingArea = booking.selectPackage.pre_addr.area;
			var addressData = result.data;
			var cityId = "";
			//拿到选择的城市id
			for(var i = 0,len = addressData.shi.length; i < len; i++){
				if(addressData.shi[i].name == bookingCity){
					cityId = addressData.shi[i].id;
				}
			}
			//生成区域列表并选中
			for(var i = 0,len = addressData.qu.length; i < len; i++){
				if(addressData.qu[i].parent_id == cityId){
					if(addressData.qu[i].name == bookingArea){
						booking.nodeId = addressData.qu[i].id;
					}
				}
			}
			booking.cartDataEditor();
		}});
	}else{
		booking.cartDataEditor();
	}
}

/**
 * 购物车数据处理
 * @method booking.cartDataEditor
 */
booking.cartDataEditor = function(){
	var data = booking.selectPackage;
	//截止时间处理,需要在日期提示前处理
	booking.sendTimeJudge();
	//星期处理
	data.weekDay = data.delivery_day.split(',');
	//人数处理
	var people = data.people_total.split(',');
	data.peopleList = [];
	for(var i = people[0],len = people[1]; i <= len; i++){
		data.peopleList.push(parseInt(i));
	}
	//是否续订
	data.renewal = booking.renewalStatus;
	//运费
	booking.deliveryFee = base.setNumberDecimals(data.freight);
	//首次配送日期提示
	var nextWeekDate = base.nextWeekDate(data.weekDay[0],booking.sendTimeRate);
	data.weekTips = nextWeekDate.month + "月" + nextWeekDate.day + "日";
	var date = new Date(); // 获取当前时间
	var today = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" +date.getDate();
	var nextWeekDay = nextWeekDate.year + "-" + nextWeekDate.month + "-" + nextWeekDate.day;
	var getUnixTime = nextWeekDay + " 0:0:0";
	booking.firstWeekTime = base.getUnixTime(getUnixTime);
	data.weekTipsGap = base.daysBetween(today,nextWeekDay);

	common.renderTpl("#app_content",'booking/booking_cart',data);
	//设置导航样式
	navigation.commonStyle();
	//计算价格
	booking.cartCount();
	$('body').scrollTop(0);
}

/**
 * 订悦购物车价格计算
 * @method booking.cartCount
 */
booking.cartCount = function(){
	var bookingFrequency = 0;   //频次
	var bookingPeopleNum = 0;    //人数
	var bookingTime = 0;     //周期
	var bookingPrice = 0;    //周期价格
	var bookingPeoplePrice = 0;   //每人每次单价
	var totalPrice = 0;     //总价

	$('#bookingFrequency li').each(function(){
		if($(this).hasClass('current')){
			bookingFrequency = parseInt($(this).data('para'));
			booking.bookingFrequency = bookingFrequency;
			booking.bookingFrequencyName = $(this).html();
		}
	});
	$('#bookingPeopleNum li').each(function(){
		if($(this).hasClass('current')){
			bookingPeopleNum = parseInt($(this).data('para'));
			booking.bookingPeopleNum = bookingPeopleNum;
		}
	});
	$('#bookingTime li').each(function(){
		if($(this).hasClass('current')){
			bookingTime = parseInt($(this).data('para'));
			bookingPrice = $(this).data('price');
			bookingPeoplePrice = base.setNumberDecimals(bookingPrice/(bookingTime*7),100);
			booking.bookingTimePrice = bookingPrice;
			booking.bookingTime = bookingTime;
		}
	});
	//公式：周期价格 * 人数 + 运费 * 周期 * 频次
	totalPrice = bookingPrice * bookingPeopleNum + booking.deliveryFee * bookingTime * booking.bookingFrequency;
	$('#bookingPrice').html(bookingPeoplePrice);
	$('#bookingCartTotal').html(base.setNumberDecimals(totalPrice));
}

/**
 * 立即预订,去付款页面
 * @method booking.goToPay
 */
booking.goToPay = function(){
	booking.deliveryDay = "";
	if($('#bookingCartAddress p').hasClass('nodata') || $('#bookingNickname').text() == ""){
		tipsBox.createAlertBox('请填写你的收货地址信息～');
		return false;
	}

	if($('input[name="riskTips"]:checked').val() != 1){
		tipsBox.createAlertBox('请阅读并同意《缤果订悦条款》');
		return false;
	}

	//设置传递数据
	$('#bookingDay li').each(function(){
		if($(this).hasClass('current')){
			if(booking.deliveryDay == ""){
				booking.deliveryDay += parseInt($(this).data('para'));
			}else{
				booking.deliveryDay += ',' + parseInt($(this).data('para'));
			}
		}
	});

	var week = booking.deliveryDay.split(',');
	var data = {
		title: booking.selectPackage.title     //套餐标题
		,week: week     //配送日期
		,people_total: booking.bookingPeopleNum     //人数
		,deliveryFrequency: booking.bookingFrequency    //频次
		,deliveryFrequencyName: booking.bookingFrequencyName    //频次名称
		,bookingTime: booking.bookingTime
		,totalPrice: $('#bookingCartTotal').html()     //总价
		,username: $('#bookingNickname').html()
		,cellphone: $('#bookingPhone').html()
		,province: $('#bookingProvince').html()
		,city: $('#bookingCity').html()
		,area: $('#bookingArea').html()
		,address: $('#bookingAddresss').html()
		,thu_img: booking.selectPackage.thu_img
		,bookingDayTips: $('#bookingDayTips').html()    //首次配送时间
		,bookingDayGap: $('#bookingDayGap').html()     //首次配送在几天后
	}
	$('#bookinCart').hide();
	common.renderTpl("#bookingPay",'booking/booking_pay',data);
	$('#bookingPay').show().css('min-height',(config.height - 100) + 'px');
	if(window.location.host == "m2.bingofresh.com"){
		$('#sendPay').hide();      //隐藏货到付款选项
	}

	//重新设置标题
	navigation.commonStyle('bookingPay');
	//设置底部按钮
	navigation.commonFooterTpl("提交订单", "","booking.submitOrder()");
	$('body').scrollTop(0);
}

/**
 * 购物车页频次、配送、人数、周期选择
 * @method booking.selectItem
 * @param {Object} _this dom对象
 * @param {String} dom 父元素
 */
booking.selectItem = function(_this,dom){
	if(_this.hasClass('current')){
		return false;
	}

	if(dom == '#bookingDay' && booking.navClass == 'fastdiet'){
		//如果套餐是轻断食，不可改变时间
		return false;
	}

	$(dom + " li").each(function(){
		$(this).removeClass('current');
	});
	_this.toggleClass('current');

	//改变配送日期,不需要计算价格
	if(dom == '#bookingDay'){
		//处理截止时间
		booking.sendTimeJudge();
		//改变星期的日期提示
		var nextWeekDate = base.nextWeekDate(_this.data('para'),booking.sendTimeRate);
		var html = nextWeekDate.month + "月" + nextWeekDate.day + "日";
		var date = new Date(); // 获取当前时间
		var today = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" +date.getDate();
		var nextWeekDay = nextWeekDate.year + "-" + nextWeekDate.month + "-" + nextWeekDate.day;
		var getUnixTime = nextWeekDay + " 0:0:0";
		booking.firstWeekTime = base.getUnixTime(getUnixTime);
		$('#bookingDayTips').html(html);
		$('#bookingDayGap').html(base.daysBetween(today,nextWeekDay));
		return false;
	}

	//改变人数，改变周期的总价，不包含运费
	if(dom == "#bookingPeopleNum"){
		$('#bookingTime li').each(function(){
			var price = base.setNumberDecimals(_this.data('para') * $(this).data('price'));
			var html = $(this).data('para') + "周(" + price + "元)";
			$(this).html(html);
		});
	}

	//改变周期，改变单价，改变运费(需要先计算价格booking.cartCount)
	if(dom == '#bookingTime' ){
		var bookingTime = parseInt(_this.data('para'));
		// var bookingPrice = _this.data('price');
		// var bookingPeoplePrice = base.setNumberDecimals(bookingPrice/(bookingTime*7),100);
		// $('#bookingPrice').html(bookingPeoplePrice);

		//运费不为0，改变运费
		if(booking.deliveryFee != 0){
			//总运费 = 运费单价 * 周期 * 频次
			var totalFee = booking.deliveryFee * bookingTime * booking.bookingFrequency;
			$('#deliveryTotalFee').html(totalFee);
			$('#deliveryNum').html(bookingTime * booking.bookingFrequency);
		}
	}

	//计算价格
	booking.cartCount();
}

/**
 * 判断当前时间是否在截止时间内
 * @method booking.sendTimeJudge
 */
booking.sendTimeJudge = function(){
	if(booking.selectPackage.stop_time_status != 1){
		return false;
	}
	var nowDateC = Math.round(new Date().getTime()/1000);    //拿到当前时间的时间戳
	//拿到本周六的时间，如果本周六减截止时间大于7,就不是本周的
	var date6 = base.nextWeekDate(6,0);    //本周六日期
	var dateDate6 = new Date(date6.year,date6.month - 1,date6.day);
	dateDate6.setHours(23);      //设置小时
	dateDate6.setMinutes(59);     //设置分钟
	dateDate6.setSeconds(59);     //设置秒
	var dateDate6c = Math.round(dateDate6.getTime()/1000);     //拿到本周六23:59:59的时间戳
	var r1 = (dateDate6c - parseInt(booking.selectPackage.stop_time))/86400;
	//判断当前时间是否大于截止时间，且截止时间要在本周内
	if(nowDateC > parseInt(booking.selectPackage.stop_time) && r1 <= 7){
		// console.log("位于截止时间内");
		booking.sendTimeRate = 2;
	}else{
		booking.sendTimeRate = 1;
	}
}

/**
 * 进入地址填写页
 * @method booking.address
 */
booking.address = function(){
	if($('#bookingAddress').html() != ""){
		//已经渲染过了
		$('#bookinCart').hide();
		$('#bookingAddress').show();
		//重新设置标题
		navigation.commonStyle('bookingAddress');
		//设置底部按钮
		navigation.commonFooterTpl("提交地址", "","booking.submitAddress()");
		return false;
	}

	if(booking.bookingAddress != null){
		//如果已经获取过
		booking.addressProcessing(booking.bookingAddress);
		return false;
	}

	var url = api_host + "/Api/Subscription/subscription_address_list";
	var openid = user.userBase.bingo_openid;
	if (openid == undefined || openid == null || openid.length == 0){
	    return false;
	}
	var data = {
		bingo_access_token: openid
		,bingo_openid: openid
	};
	$.ajax({type: 'post', url: url, data: data, dataType: 'json', success: function (result) {
		booking.bookingAddress = result.data;
		booking.addressProcessing(result.data);
	}});
}

/**
 * 处理收货地址填写页数据
 * @method booking.addressProcessing
 * @param {Object} data 收货地址数据
 */
booking.addressProcessing = function(data){
	if(booking.renewalStatus == 1){   //续订带入旧地址
		data.bookingNickname = $('#bookingNickname').text();
		data.bookingPhone = $('#bookingPhone').text();
		data.bookingProvince = $('#bookingProvince').text();
		data.bookingCity = $('#bookingCity').text();
		data.bookingArea = $('#bookingArea').text();
		data.bookingAddresss = $('#bookingAddresss').text();

		var addressData = booking.bookingAddress;
		var cityId = "";
		//拿到选择的城市id
		for(var i = 0,len = addressData.shi.length; i < len; i++){
			if(addressData.shi[i].name == data.bookingCity){
				cityId = addressData.shi[i].id;
			}
		}

		var selectList = '<option value="-1">请选择配送区域</option>';
		//生成区域列表并选中
		for(var i = 0,len = addressData.qu.length; i < len; i++){
			if(addressData.qu[i].parent_id == cityId){
				if(addressData.qu[i].name == data.bookingArea){
					selectList += '<option value="' + addressData.qu[i].id + '" data-send="' + addressData.qu[i].send_type + '" selected>' + addressData.qu[i].name + '</option>';
					booking.nodeId = addressData.qu[i].id;
				}else{
					selectList += '<option value="' + addressData.qu[i].id + '" data-send="' + addressData.qu[i].send_type + '">' + addressData.qu[i].name + '</option>';
				}
			}
		}
	}

	$('#bookinCart').hide();
	common.renderTpl("#bookingAddress",'booking/booking_address',data);
	$('#bookingAddress').show();
	//重新设置标题
	navigation.commonStyle('bookingAddress');
	//设置底部按钮
	navigation.commonFooterTpl("提交地址", "","booking.submitAddress()");

	if(booking.renewalStatus == 1){
		//写入区域
		$('#league').html(selectList);
	}
}

/**
 * 返回购物车
 * @method booking.addressReturnCart
 */
booking.addressReturnCart = function(){
	$('#bookingAddress').hide();
	$('#bookingPay').hide();
	$('#bookingSuccess').hide();
	$('#bookinCart').show();
	//重新设置返回按钮
	navigation.commonStyle();
	//清空底部按钮
	$('#app-footer-main').html('');
	$('body').scrollTop(0);
}

/**
 * 选择省份
 * @method booking.selectProvinces
 */
booking.selectProvinces = function(){
	var html = "";
	$('#provinces option').not(function(){
		if(this.selected){
			html = this.text;
		}
	});
	$('#showProvinces').val(html);
}

/**
 * 选择城市
 * @method booking.selectCity
 */
booking.selectCity = function(){
	var html = "";
	$('#city option').not(function(){
		if(this.selected){
			html = this.text;
			if(this.dataset.send == 2){
				//第三方配送城市
				booking.sendType = 2;
				$('#bookingAreaBox').hide();
				$('#bookingSendTips').show();
			}else{
				booking.sendType = 1;
				$('#bookingAreaBox').show();
				$('#bookingSendTips').hide();
			}
		}
	});
	$('#showCity').val(html);
	//改变区域分店列表
	booking.changeArea();
}

/**
 * 改变城市改变分店列表
 * @method booking.changeArea
 */
booking.changeArea = function(){
	var city = $('#city').val();
	if (city == -1) {
	    return false;
	}
	$('#showArea').val('');    //清空
	var data = booking.bookingAddress.qu;
	var select = '<option value="-1">请选择配送区域</option>';
	for(var i = 0,len = data.length; i < len; i++){
		if(data[i].parent_id == city){
			select += '<option value="' + data[i].id + '" data-send="' + data[i].send_type + '">' + data[i].name + '</option>';
		}
	}
    $('#league').html(select);
}

/**
 * 选择分店
 * @method booking.selectArea
 */
booking.selectArea = function(){
	var html = "";
	$('#league option').not(function(){
		if(this.selected){
			html = this.text;
			booking.nodeId = this.value;
			if(this.dataset.send == 2){
				//第三方配送区域
				booking.sendType = 2;
				$('#bookingSendTips').show();
			}else{
				booking.sendType = 1;
				$('#bookingSendTips').hide();
			}
		}
	});
	$('#showArea').val(html);
	$('#address').val('');
}

/**
 * 提交地址
 * @method booking.submitAddress
 */
booking.submitAddress = function(){
 	if(!booking.checkSubmitAddress()){
 		return false;
 	}
 	var name = $("#name").val();
 	var phone = $("#phone").val();
 	var provinces = $('#showProvinces').val();
 	var city = $('#showCity').val();
 	var area = $('#showArea').val();
 	var address = $("#address").val();

 	if(provinces == undefined){
 		provinces = "广东省";     //默认广东省
 	}

 	booking.addressReturnCart();

 	var html = '<p><span id="bookingNickname">' + name +'</span>&nbsp;&nbsp;&nbsp;<span id="bookingPhone">' + phone + '</span></p>';
 	    html += '<p><span id="bookingProvince">' + provinces + '</span><span id="bookingCity">' + city + '</span><span id="bookingArea">' + area + '</span><span id="bookingAddresss">' + address + '</span></p>';
 	    html += '<i></i>';

 	$('#bookingCartAddress').html(html);
 }

 /**
  * 检查提交的地址数据是否正确
  * @method booking.checkSubmitAddress
  */
booking.checkSubmitAddress = function(){  //检查提交数据是否正确
	var name = $("#name").val();
	if(name == ""){
		tipsBox.createAlertBox("请输入收获人姓名");
		return false;
	}
	var phone = $("#phone").val();
	if(phone == ""){
		tipsBox.createAlertBox("请输入联系方式");
		return false;
	}
	var reg = /^13[\d]{9}$|^14[0-9]\d{8}|^15[0-9]\d{8}$|^17[0-9]\d{8}|^18[0-9]\d{8}$/g;
	if (!reg.test(phone)) {
	    tipsBox.createAlertBox('输入的手机号码有误');
	    return false;
	}
	var provinces = $('#provinces').val();
	if(provinces == "-1"){
		tipsBox.createAlertBox("请选择配送省份");
		return false;
	}
	var city = $("#city").val();
	if (city == "-1") {
		tipsBox.createAlertBox("请选择配送城市");
		return false;
	}
	if(city != 0) {
		var league = $("#league").val();
		if (league == "-1" && $('#bookingAreaBox').css('display') == "table-row") {
			tipsBox.createAlertBox("请选择配送区域");
			return false;
		}
	}
	var address = $("#address").val();
	if(address == ""){
		tipsBox.createAlertBox("请输入具体的收货地址");
		return false;
	}
	return true;
}

/**
 * 提示柜
 * @method booking.showWrapAlert
 * @method {Number} type 0地址提示/1风险提示/-1关闭
 */
booking.showWrapAlert = function(type){
	var tips = "";
	switch(Number(type)){
		case -1:
			$('#bookingCartTips').hide();
			return false;
			break;
		case 0:
			//地址提示
			tips = "<h1>缤果物流覆盖区域</h1>";
			tips += "<p>中山配送区域：东区、三乡、西区、沙溪、南区、大涌</p>";
			tips += "<p>(具体配送区域请咨询缤果客服)</p>";
			break;
		case 1:
			//风险提示
			switch(booking.navClass){
				case 'fruit':
					//水果
					tips = "<h1>缤果水果订悦服务条款</h1>";
					tips += "<p>请认真阅读缤果订悦使用条款（以下简称“条款”）。这些条款非常重要，将影响你的消费权益，所以请仔细阅读。</p>";
					tips += "<p>1、缤果订悦是中山市宾哥网络科技有限公司（下称为“缤果”）推出的定制类服务，对开通配送区域的用户提供此服务；缤果可能会根据市场因素在一定范围内调整价格及数量，不同套餐所包含的产品数量、重量及价格可能会变动，要了解更详细的的套餐信息，请查阅每期的订悦页面。同时，请务必注意，订悦只承诺保证套餐所提供的水果数量，重量没有明确标注。</p>";
					tips += "<p>2、针对订悦套餐的具体包装，缤果生鲜会视季节，食品种类，在保证新鲜度及不影响质量的前提下，灵活采取各类包装材料，如胶袋，纸盒、纸袋等。</p>";
					tips += "<p>3、订悦所包含产品经本人或他人代当面验货签收后，视为该套餐无质量问题，不能申请退货；签收时仔细核对：产品品类、数量、产品质量进行检查，如有异常，请你现场提出或者咨询送货员；</p>";
					tips += "<p>4、如存在以下情况可以拒收或请求送货员更换:①商品存在严重质量问题（如严重腐烂等）；②发错商品、商品数量有误等；</p>";
					tips += "<p>5、订购一个月以上（含一个月）由客户个人原因造成的退换货情况：(1)、个人口味偏好；(2)、产品色泽感观差异；(3)、或其他非质量问题原因，缤果将按原价扣除已享受的服务费用，退还剩余批次套餐款给用户；如用户享受优惠（如打折，免运费等），所享受的服务及产品价格将不再享受优惠。</p>";
					tips += "<p>6、如遇到恶劣气候、配送途中的突发等非人为因素发生严重质量问题时，可要求退换相同或等价的商品。</p>";
					tips += "<p>7、订悦套餐每次配送将对所配送的水果配以注意事项或禁忌等简单说明，仅作为一般用户参考意见；有特殊体质或其他疾病的，进食套餐水果前请咨询医生专业建议。 </p>";
					tips += "<p>8、订悦套餐所包含产品经缤果精心挑选，收到货后请尽早使用，如因用户储存方法不当或其他原因引发的质量问题，用户个人将承担所带来的损失。</p>";
					tips += "<p>9、缤果微信商城、缤果App图片及信息仅供参考，商品以实物为准，拍摄灯光和显示器色差可能会造成产品实物和图片有少许出入的情况，不属于质量问题</p>";
					tips += "<p>10、订悦享受缤果全程冷链的配送服务，配送免收取运费，该套餐实行定期配送，用户如有特许原因需要变更地址或时间，或者中途暂停配送的，请提前48小时暂停，或48小时前与缤果客服联系，以便协助您暂停。因个人因素造成送货无人签收的，所造成的损失由用户承担。</p>";
					tips += "<p>11、订悦支付方式适用微信支付，不支持货到付款。</p>";
					tips += "<p>12、订悦服务不支持用户自己手动取消，如有特殊情况需要取消订悦服务的，请在订悦产品配送前48小时于缤果客服取得联系，以便为您进行取消。</p>";
					tips += "<p>13、缤果（中山市宾哥网络科技有限公司）将在法律允许范围内保留最终解释权。</p>";
					break;
				case 'food':
					//半熟食
					tips = "<h1>这是这是半熟食标题</h1>";
					tips += "<p>这是这是半熟食内容</p>";
					break;
				case 'fastdiet':
					//轻断食
					tips = "<h1>《轻断食风险提示》</h1>";
					tips += "<p>风险提示：缤果轻断食计划目前处于测试阶段，我们为参与测试的种子用户提供特别的优惠，但也请明确参加测试计划可能存在的以下风险：</p>";
					tips += "<p>1，缤果轻断食计划旨在为用户提供一个健康营养的餐饮选择，并无任何减重或疗效承诺。</p>";
					tips += "<p>2，轻断食计划目前处于招募阶段。由于最终参与计划的人数无法预知，项目有可能会因为人数不足而失败。万一项目失败，您支付的全部款项将会被原路退回给您。具体到款时间为缤果发起退款后的3~5个工作日，不同支付平台的退款时间会有不同，请谅解</p>";
					tips += "<p>3，招募成功后，计划也有可能因为成本或者市场风险而随时终止。万一项目被临时终止，缤果将会提前一周通知您，并按比例退还还没有消费的款项。</p>";
					tips += "<p>4，我们将会尽力在早上11点前把餐食送到，但也未免出现其他用户拖延导致延迟配送时间的情况。</p>";
					tips += "<p>5，菜品图片只供参考。受限于不同食材的价格波动，有可能菜品会临时变动，我们将会在配餐的前一天通过微信或者短信通知 </p>";
					tips += "<p>6，在第一次配餐前72小时以前，参与测试的用户都可以随时退出计划并获得退款。</p>";
					tips += "<p>7，在第一次配餐前72小时以后，测试期间由于系统尚未完善，参与测试的用户将无法中途暂停或取消。由于参与者自身的原因导致无法接收餐食的，也将无法获得退款。</p>";
					tips += "<p>8，轻断食并不适合所有人群，请参与前务必了解自身身体状况，必要时咨询医生建议</p>";
					tips += "<p>9，缤果（中山市宾哥网络科技有限公司）将在法律允许范围内保留最终解释权。</p>";
					break;
			}
			break;
	}
	$('#bookingShowWrapAlert').html(tips);
	$('#bookingCartTips').show();
}

/**
 * 阅读风险提示
 * @method boooking.checkboxSelect
 */
booking.checkboxSelect = function(){
	$('#riskTips').next('label').toggleClass('current');
}

/**
 * 订悦提交订单页面
 * @method booking.submitOrder
 */
booking.submitOrder = function(){
	if(!base.checkBtnLock()){
		return false;
	}
	if(booking.nodeId == -1){
		tipsBox.createAlertBox('提交失败，请退出商城重试，如果情况依旧，请联系我们的客服');
		return false;
	}

	var payType = $("input[name='pay_type']:checked").val();    //支付方式

	var url = api_host + "/Api/Subscription/subscription_order_submit";
	var openid = user.userBase.bingo_openid;
	if (openid == undefined || openid == null || openid.length == 0){
	    return false;
	}
	var order_type = 1;
	switch(booking.navClass){
		case 'fruit':
			//水果
			order_type = 1;
			break;
		case 'food':
			//半熟食
			order_type = 2;
			break;
		case 'fastdiet':
			//轻断食
			order_type = 3;
			break;
		default:
			order_type = 1;
	}

	var delivery_fee = base.setNumberDecimals(booking.deliveryFee * booking.bookingFrequency * booking.bookingTime);

	var data = {
		bingo_access_token: openid
		,bingo_openid: openid
		,bingo_appid: config.appid   //数据来源 1:微信web客户端 ,2:IOS客户端 ,3:ANDROID客户端
		,pid: booking.selectPackage.product_id     //产品id
		,price: booking.bookingTimePrice     //一个人单价
		,node_id: booking.nodeId    //分店id
		,league_id: 35    //总仓店id
		,order_type: order_type     //订单类型:1-水果套餐,2-半成品菜,3-轻断食
		,order_status: 0    //订单状态:-2.退货订单,-1.取消订单,0.待处理订单,2.已完成订单
		,pay_type: payType    //支付类型:0.货到付款,1.微信支付
		,pay_order: 0   //支付状态:0.未支付,1.已支付
		,username: $('#bookingNickname').html()
		,cellphone: $('#bookingPhone').html()
		,province: $('#bookingProvince').html()
		,city: $('#bookingCity').html()
		,area: $('#bookingArea').html()
		,address: $('#bookingAddresss').html()
		,voucher_id: ""    //优惠券id
		,people_total: booking.bookingPeopleNum    //人数
		,bingo_delivery: 1    //是否缤果配送:1-缤果配送,2-第三方配送
		,delivery_day: booking.deliveryDay      //配送日期,多选逗号分隔
		,delivery_frequency: booking.bookingFrequency    //频次
		,cycle: booking.bookingTime     //周期
		,delivery_fee: delivery_fee   //运费
		,week_after_next: booking.selectPackage.stop_time_status
		,first_week_time: booking.firstWeekTime    //第一周配送时间
	}
	$.ajax({type: 'post', url: url, data: data, dataType: 'json', success:function(result){
		base.clearBtnLock();
		if(result.status != 1){
			tipsBox.createAlertBox(result.data);
			return false;
		}
		var locationUrl = "";
		var host = window.location.host;
		switch(payType){
			case '0':
				//货到付款
				if (host  == "test.bingofresh.com"){//测试服务器
					locationUrl = 'http://test.bingofresh.com/v3.7/home.php#/booking_success/' + result.data.order_id;
				} else if (host == "m.bingofresh.com" || host == "m2.bingofresh.com"){//正式服务器
					locationUrl = 'http://m2.bingofresh.com/v3.7/home.php#/booking_success/' + result.data.order_id;
				}else{
					locationUrl = 'http://web.bingo.com/v3.7/home.php#/booking_success/' + result.data.order_id;
				}
				break;
			case '1':
				//微信支付
				if (host  == "test.bingofresh.com"){//测试服务器
				    locationUrl = 'http://pay.bingofresh.com/wxpay_new/SubscriptionPay.php?is_test=1&order_id=' + result.data.order_id + '&open_id=' + openid + '&pid=' + booking.selectPackage.product_id;
				    // locationUrl = 'http://pay.bingofresh.com/wxpay_new/SubscriptionPay.php?is_test=1&order_id=' + result.data.order_id + '&open_id=oge3_t6chURw3Ikf4VBMTgBgKcbc&pid=' + booking.selectPackage.product_id;
				} else if (host == "m.bingofresh.com" || host == "m2.bingofresh.com"){//正式服务器
				    locationUrl = 'http://pay.bingofresh.com/wxpay_new/SubscriptionPay.php?order_id=' + result.data.order_id + '&open_id=' + openid + '&pid=' + booking.selectPackage.product_id;
				}
				break;
		}
		window.location.href = locationUrl;
	}});
}

/**
 * 下单成功提示页面
 * @method booking.submitSuccess
 * @param {Object} orderId 订单id
 */
booking.submitSuccess = function(orderId){
	var url = api_host + "/Api/Subscription/get_order_info";
	var openid = user.userBase.bingo_openid;
	if (openid == undefined || openid == null || openid.length == 0){
	    return false;
	}
	var data = {
		bingo_access_token: openid
		,bingo_openid: openid
		,order_id: orderId
	}

	$.ajax({type: 'post', url: url, data: data, dataType: 'json', success:function(result){
		if(result.status != 1){
			tipsBox.createAlertBox(result.data);
			common.loaded(0);
			return false;
		}
		if(result.data == ""){
			window.location.href = "#/booking";
			return false;
		}
		var successData = result.data[0];
		successData.delivery_day = successData.delivery_day.split(',');
		successData.className = "水果";
		switch(successData.order_type){
			case '1':
				successData.className = "水果";
				break;
			case '2':
				successData.className = "风味餐";
				break;
			case '3':
				successData.className = "轻断食餐";
				break;
			default:
				successData.className = "水果";
		}
		common.renderTpl("#app_content",'booking/booking_success',successData);
		common.loaded(0);
		$('#bookingSuccess').css('min-height',(config.height - 50) + 'px');

		//设置底部按钮
		navigation.commonFooterTpl("查看我的订悦", "#/booking_order","");
		$('body').scrollTop(0);
	}});
}

/**
 * 订悦产品详情页
 * @method booking.view
 */
booking.view = function(){
    common.renderTpl("#app_content",'booking/booking_view',{});
	common.loaded(0);
	navigation.simpleStyle('查看菜谱');
}

/**
 * 订悦不可选选项
 * @method booking.notselectItem
 */
booking.notselectItem = function(){
	tipsBox.createAlertBox('订悦内测期间，只能选择 1周 | 2人 | 周二 配送，不便之处敬请原谅');
}

/**
 * 订悦订单列表入口
 * @method booking.order
 * @param {String} type 类型
 */
booking.order = function(type){
    common.renderTpl("#app_content",'booking/booking_order',{});
	common.loaded(0);

	$('.header-common-inner td:last-child').hide();

	if(type == "" || type == undefined || type == null){
		// 默认选择水果
		type = 'fruit';
	}
	//处理头部菜单
	booking.orderMenu(type);
}

/**
 * 订单页头部菜单处理
 * @method booking.orderMenu
 * @param {String} type 类型
 */
booking.orderMenu = function(type){

	$('#header-common-main span').removeClass('ft-color');
	$('#header-common-main span').removeClass('bd-color');
	$('#'+type+'-btn').addClass('ft-color');
	$('#'+type+'-btn').addClass('bd-color');

	$("#order_tabs .active").hide();
	$("#order-"+type+"-list").show();
	$("#order_tabs .active").removeClass("active");
	$("#order-"+type+"-list").addClass("active");

	if($("#order-" + type + "-list").html() == ""){   //为空时获取接口数据
		booking.getOrderList(type);
	}
}

/**
 * 获取订单列表
 * @method booking.getOrderList
 * @param {String} type 类型
 */
booking.getOrderList = function(type){

	//加载loading
	$('.valuation-loading-mark').show();
	$('.valuation-loading-box').show();

	var url = api_host + "/Api/Subscription/subscription_order_list";
	var openid = user.userBase.bingo_openid;
	if (openid==undefined || openid==null || openid.length==0){
	    return false;
	}

	var order_type = 1;
	switch(type){
		case 'fruit':
			order_type = 1;
			break;
		case 'food':
			order_type = 2;
			break;
		case 'fastdiet':
			order_type = 3;
			break;
	}

	var data = {
		bingo_access_token: openid
		,bingo_openid: openid
		,order_type: order_type
	};
	$.ajax({type: 'post', url: url, data: data, dataType: 'json', success:function(result){
		if(result.status == 0){
			tipsBox.createAlertBox(result.data);
			// 关闭loading
			$('.valuation-loading-mark').hide();
			$('.valuation-loading-box').hide();
			return false;
		}
		if(result.data == ""){
			common.noFoundResult('还没有订悦订单','#order-' + type +'-list');
			// 关闭loading
			$('.valuation-loading-mark').hide();
			$('.valuation-loading-box').hide();
			return false;
		}
		// var dataList = {};
		// dataList.data = [];
		// for (var i = result.data.length - 1; i >= 0; i--) {
		// 	dataList.data.push(result.data[i]);
		// }
		var iddom = '#order-' + type +'-list';
		var dom = 'booking/booking_order_' + type;
		common.renderTpl(iddom,dom,result);

		// 关闭loading
		$('.valuation-loading-mark').hide();
		$('.valuation-loading-box').hide();

	}});

}

/**
 * 询问订单是否暂停一周
 * @method booking.askStopweek
 * @param {Number} orderno 订单id
 * @param {Number} index 订单顺序
 */
booking.askStopweek = function(orderno,index){
   	if(!base.checkBtnLock()){    //防止重复提交
		return false;
    }
	var monday = $('#monday_' + orderno + '_' + index).html();
	var week = $('#week_' + orderno + '_' + index).html();
	tipsBox.createConfirmBox('选择暂停本次后，' + monday + '(' + week + ')将不会给你配送，自动延缓到下次恢复配送。', 'booking.stopweek', orderno, '暂停本次');
	base.clearBtnLock();
}

/**
 * 订单确定暂停一周
 * @method booking.stopweek
 * @param {Number} orderno 订单id
 */
booking.stopweek = function(orderno){
   	if(!base.checkBtnLock()){    //防止重复提交
		return false;
    }
	tipsBox.hideTipsBox();
	var url = api_host + "/Api/Subscription/stopweek";
	var openid = user.userBase.bingo_openid;
	if (openid==undefined || openid==null || openid.length==0){
	    return false;
	}
	var data = {
		bingo_access_token: openid
		,bingo_openid: openid
		,orderno: orderno
		,stop: -1
	};
    $.ajax({type: 'post', url: url, data: data, dataType: 'json', success:function(result){
    	if(result.status != 1){
    		tipsBox.createAlertBox(result.data);
    		base.clearBtnLock();
    		return false;
    	}
    	tipsBox.createAlertBox("暂停成功～");
    	$('#tips-box a').attr('onclick','booking.stopweekLocation()');
    	base.clearBtnLock();
    }});
}

/**
 * 暂停后刷新页面
 * @method booking.stopweekLocation
 */
booking.stopweekLocation = function(){
	var class_mark = "fruit";
	$('#header-common-main li').each(function() {
		if($(this).find('span').hasClass('ft-color')){
			class_mark = $(this).data('class');
		}
	});
	booking.order(class_mark);
}


/**
 * 订悦退订入口
 * @method booking.unsubscribe
 * @param {String} orderId 订单id
 */
booking.unsubscribe = function(orderId){
	var url = api_host + "/Api/Subscription/get_order_info";
	var openid = user.userBase.bingo_openid;
	if (openid == undefined || openid == null || openid.length == 0){
	    return false;
	}
	var data = {
		bingo_access_token: openid
		,bingo_openid: openid
		,order_id: orderId
	}
	$.ajax({type: 'post', url: url, data: data, dataType: 'json', success:function(result){
		if(result.status != 1){
			common.loaded(0);
			tipsBox.createAlertBox(result.data);
			return false;
		}
		if(result.data == ""){
			common.loaded(0);
			tipsBox.createAlertBox("请联系客服退订～");
			$('#tips-box a').attr('href','#/booking');
			return false;
		}
		var data = result.data[0];
		data.fee = base.setNumberDecimals(data.unsubscribe_price - data.price * data.people_total);

		common.renderTpl("#app_content",'booking/booking_unsubscribe',data);
		common.loaded(0);

		//设置底部按钮
		navigation.commonFooterTpl("我要退订", "","booking.askUnsubscribe(" + data.order_id + ")");

		$('#bookingUnsubscribe').css('min-height',(config.height - 100) + 'px');
		$('body').scrollTop(0);
	}});
}

/**
 * 询问是否退订
 * @method booking.askUnsubscribe
 * @param {String} orderId 订单id
 */
booking.askUnsubscribe = function(orderId){
	tipsBox.createConfirmBox('退订后将在7个工作日内将剩余金额退还，微信支付原路退回，货到付款则退到账户余额。已配送的产品将不可退款，是否继续？', 'booking.sureUnsubscribe', orderId, '确认退订');
}

/**
 * 订悦执行退订
 * @method booking.sureUnsubscribe
 * @param {Number} orderId
 */
booking.sureUnsubscribe = function(orderId){
   	if(!base.checkBtnLock()){    //防止重复提交
		return false;
    }
	tipsBox.hideTipsBox();
	var url = api_host + "/Api/Subscription/unsubscribe";
	var openid = user.userBase.bingo_openid;
	if(openid == "" || openid == undefined || openid == null){
		return false;
	}
	var data = {
		bingo_access_token: openid
		,bingo_openid: openid
		,order_id: orderId
		,from: 0
	}
	$.ajax({type: 'post', url: url, data: data, dataType: 'json',success:function(result){
		base.clearBtnLock();
		if(result.status != 1){
			tipsBox.createAlertBox(result.data);
			return false;
		}
		$('#bookingUnsubscribe').hide();
		$('#bookingUnsubscribeSuccess').show().css('min-height',(config.height - 140) + 'px');

		//设置底部按钮
		navigation.commonFooterTpl("返回缤果商城", ".","");
	}});
}

/**
 * 已预订/暂停接单，无法订悦
 * @method booking.uncanGoCart
 * @param {Number} type 1已预订/2已满员
 */
booking.uncanGoCart = function(type){
	var tips = "";
	switch(booking.navClass){
		case "fruit":
			tips = "你已订悦了水果服务，无法重复订悦";
			break;
		case "food":
			tips = "你已订悦了半熟食服务，无法重复订悦";
			break;
		case "fastdiet":
			tips = "你已订悦了轻断食服务，无法重复订悦";
			break;
		default:
			tips = "你已订悦了水果服务，无法重复订悦";
	}
	if(type == 2){
		tips = "非常抱歉，确认采购中，暂停接单～";
	}
	tipsBox.createConfirmBox(tips, 'booking.orderUrl', '', '我的订悦');
}

/**
 * 跳转到订单页函数
 * @method booking.orderUrl
 */
booking.orderUrl = function(){
	window.location.href = "#/booking_order";
}

/**
 * 付款方式切换
 */
$('#booking-paytype input').live('click',function() {
    $(this).parents('ul').find('i').removeClass('current');
    $(this).prev().addClass('current');
});
/**
 * Created by keepsilent on 16/7/5.
 */
var broadcast = {};
broadcast.page = 1;


/**
 * 直播间初始化
 * @method broadcast.init
 */
broadcast.init = function() {
    broadcast.page = 1;
    if(home.productList != null) {
        broadcast.createIndexTpl (home.productList.video);
    } else {
        var data = home.get_product_param();
        $.ajax({type:'post',url:data.url,data:data.param,dataType: 'json',success:function(result) {
            if(result.status == 1) {
                broadcast.createIndexTpl (result.data.video);
            }
        }});
    }
}

/**
 * 渲染直播间
 * @param {Objcet} data 数据
 */
broadcast.createIndexTpl = function(data) {
    common.renderTpl('#app_content','broadcast/broadcast_list',{});
    if(data != '') {
        $('#broadcast-top').show();
        common.renderTpl('#broadcast-top','broadcast/broadcast_top',data);
        broadcast.imgRate('#broadcast-top img');
        broadcast.imgRate('#broadcast-top a');
    }
    common.loaded(0);
    broadcast.addNewData();
}


/**
 * 直播间图片比率 长:宽 1.8:1
 * @param className 元素名字
 */
broadcast.imgRate = function(className) {
    var width = $(className).width();
    $(className).height(width * 0.55);
    return false;
}

/**
 * 商城首页banner
 * @param data
 */
broadcast.banner = function(data) {
    if(data == '' ) {
        return false;
    }

    if(data.type.indexOf(home.cur_product_class) == -1) {
        return false;
    }

    common.renderTpl('#top-video-box','broadcast/broadcast_banner',data);
    $('#top-video-box').show();
    broadcast.imgRate('#top-video-box img');
    broadcast.imgRate('#video-banner-cover');
}

/**
 * 加载新的数据
 * @method broadcast.addNewData
 */
broadcast.addNewData = function() {
    $('#broadcast-load').dropload({
        scrollArea : window,      //滑动区域，默认是绑定元素本身，但是不绑定window在iphone上会出错
        domDown : {      //下方DOM上拉时自定义父元素，会出现绑定的元素下面
            domClass   : 'dropload-down',      //整个自定DOM的样式
            domRefresh : '<div class="dropload-refresh">↓下拉加载更多</div>',     //上拉状态
            domLoad    : '<div class="dropload-load"><span class="loading"></span>加载中...</div>',      //正在加载中
            domNoData  : '<div class="dropload-noData">无更多数据了</div>'    //没有数据更新了
        },
        loadDownFn : function(me) {
            var url= api_host + "/Api/Product/video_history_list";
            var openid = user.userBase.bingo_openid;
            var data = { bingo_access_token: openid,bingo_openid:openid, page_next:broadcast.page, pages: 6 };
            $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result) {
                if(result.status == 1) {
                    if(result.data != '') {
                        broadcast.createItemTpl(result.data);
                        broadcast.page++;
                        broadcast.imgRate('.broadcast-main-inner img');
                        broadcast.imgRate('.broadcast-main-inner a');
                        setTimeout(function () {
                            me.resetload();
                        }, 2000);// 为了测试，延迟1秒加载，每次数据加载完，必须重置
                    } else {

                        if(broadcast.page == 1) {
                            var html = '<p class="tc" style="margin-top: 15px; color: #999;">暂无其他往期视频</p>';
                            $('.broadcast-main-inner').html(html);
                        }
                        $('.dropload-down').hide();
                        me.lock('down');
                    }
                } else {
                    tipsBox.createAlertBox(result.data);
                    $('.dropload-down').hide();
                    me.lock('down');
                }
            }, error: function(xhr, type){
                tipsBox.createAlertBox("抱歉，数据加载失败，请重新尝试。如果情况依旧请联系我们客服。");
                me.resetload();// 即使加载出错，也得重置
            }});
        },
    });
}

/**
 * 渲染子视频
 * @method broadcast.createItemTpl
 * @param {Object} data 数据
 */
broadcast.createItemTpl = function(data) {
    var html = '',j = 1;
    for(var i in data) {
        data[i]['style'] = (j % 2 == 0) ? 'float:right' : '';
        html += template('broadcast/broadcast_items', data[i]);
        j++;
    }
    $('.broadcast-main-inner ul').append(html);
}
var cart={
    data: {}
};
/*初始化*/
cart.init=function(){
    cart.user_receive_time=""; //用户收货时间
    cart.user_ziti_time="";  //用户自提时间
    cart.timing_voucher = "";   //定时达超时送券名称
    cart.timing_timeout = "";   //定时达超时时间
    cart.timing_cost = "";    //定时达运费
    cart.data.cart_type=0; //0 正常水果 1特价抢购 2团购 3套装
    cart.data.all_num=0; //购物车商品总数
    cart.data.special_all_num = 0; //特价抢购商品总数
    cart.data.bag={is_join:0,not_recover_num:0}; //环保袋信息
    cart.data.bags_num=0; //环保袋数量
    cart.data.bags_fee=0; //环保袋费用
    cart.data.lower_fee=0; //减免金额
    cart.data.voucher_fee=0; //优惠券金额
    cart.data.man_x_jian_y_fee = 0; //满x减y
    cart.data.BuyNGetOne_fee = 0; //买N免1
    cart.data.discount_activity_fee = 0; //折扣费
    cart.data.dev_fee=0; //运费
    cart.data.groupbuy_fee = 0; //团购运费
    cart.data.online_pay=0; //是否只允许在线支付 1只能在线支付

    cart.data.cart_user_league = 0;
    cart.data.headOffice = _headOffice;
    cart.data.cart_environment = _is_app;
    cart.data.activity = ''; //购物车里的活动
    cart.data.online_discount_pay = 0; //打折活动支付方式有优惠，0,没有,1:有
    cart.data.last_total_fee=0, //最终订单总金额
    cart.data.AddrVo={invoiceTitle: '',fee_free:28,fee:2}; //默认低于28元,收取2元运费
    cart.data.leagueconfig={invoiceTax: 0.2}, //加盟商配置
    cart.data.package_info={id:0,pre_id:0}, //选中的套餐商品
    cart.data.sendTime={}, //送货时间
    cart.data.voucher={selected: 0,code:0}, //代金券
    cart.data.product_list=[] //购物车中产品
    cart.data.special_list=[] //购物车特价产品
    cart.data.sub_products=[] //购物车子商品
    cart.data.packbag = [];   //购物袋商品
    cart.data.timing_fee = 0; //定时达运费
    cart.data.weights = ''; //称重产品

    cart.fruit_total = 0; //购买水果总价
    cart.special_fruit_total = 0; //特价抢购水果总价

    cart.sub_product_cart = {};
    cart.sub_product_total = 0;

    cart.data.add_price = ""; //加价购
    cart.add_product_cart = { cart:{}, total: 0, selected:0 }; //用户加价购购物车
    cart.data.add_price_product = {price: 0,id: 0}, //加价购选中商品，由于要功能扩展，这个参数不会再使用

    cart.order_count = 99999999; //总订单数
    cart.shopping_bag = '';//购物袋
    cart.bag_skus = 0; //购物袋sku数
    cart.ziti_only = 0; //只显示自提
    cart.noCount = 0; //不用重新计算
    cart.order_allow_submit = 1; //订单充许提交
    cart.map_is_loaded = 0; //地图重设
    cart.data.blance_money = 0;
    cart.blance_pay_stauts = 0;  // 余额付款方式
    cart.remain_blance_stauts = 0;
    cart.disallow_voucher_status = 0; //不充许使用优惠券状态
    cart.disallow_voucher_fee = 0; //不充许使用优惠券金额
    cart.disallow_voucher_tips = ''; //不充许使用优惠券提示
    cart.ziti_addr = "";   //自提地址

};

/*初始化*/
cart.init();
/*订单类型*/

/* 数据正常可以删除 2016/05/19
cart.get_product_type=function(){
    var product_type="normal";
    if (cart.data.cart_type==1){
        product_type="special";
    }else if (cart.data.cart_type==2){
        product_type="groupbuy";
    }else if (cart.data.cart_type==3){
        product_type="package";
    }
    return product_type;
}*/


/**
 * 获得订单类型
 * @method cart.get_product_type
 * @returns {string}
 */
cart.get_product_type = function(){
    var product_type = '';
    switch (parseInt(cart.data.cart_type)) {
        case 1: //特价
            product_type = "special";
            break;
        case 2://团购
            product_type="groupbuy";
            break;
        case 3://礼盒
            product_type="package";
            break;
        default: //正常水果
            product_type = "normal";
            break;
    }
    return product_type;
}


/*获取购物车信息*/
cart.get_info=function(){
    order_or_cart = 0;    //重置收货地址模式为购物车
    //如果购物车为空，返回首页
    if (cart.data.all_num==0){
        //window.location.href="#/home";
        //return false;
    }
    var url=api_host+"/Api/Buycar/car";

    var openid=user.userBase.bingo_openid;

    if (openid==undefined || openid==null || openid.length==0){
        return false;
    }
    /*
    var buycar = getCookie('buycar');
    buycar = product_weighing.buycartAddWeights(buycar);
    var special_car = getCookie('special_car');
    console.log('特价水果',special_car);

    var product_type = cart.get_product_type();
    if(product_type != 'groupbuy' && product_type != 'special' && product_type != 'package' ) {
        if(buycar != null || product_weighing.productData.length > 0) {
            product_type = 'normal';
        }
        if(special_car != null ) {
            product_type = 'special';
        }
        if(buycar != null && special_car != null ) {
            product_type = 'blend';
        }
    }*/
    var cartBase = cart.getCartBaseInfo();

    var data={
        bingo_access_token:openid
        ,bingo_openid:openid
        ,product_type:cartBase.product_type
        ,buycar:cartBase.buycar
        ,sp_buycar:cartBase.special_car
        ,app_id:config.appid
        ,pay_type:cart.getPayMethod()
        ,is_vip:common.isVip()? 1 : 0
    };

    cart.sub_product_cart = {};
    cart.sub_product_total = 0;
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        if(result.status == "-08001"){
            $("#r").css('background','#CCC').removeAttr('onclick');
        }
        if(result.status != 1){
            tipsBox.createAlertBox(result.data);
            return false;
        }
        navigation.commonStyle();

        $('#user_enter_cart').hide();
        cart.data.bag = result.data.bag; //购物袋信息
        cart.data.packbag = result.data.packbag; //包装袋数据
        cart.bag_skus = result.data.bag_skus; //包装袋suk数
        cart.ziti_addr = result.data == undefined ? "" : result.data.ziti.abholung_address; //自提地址
        cart.order_count = result.data.order_count || cart.order_count; //用户购买次数
        cart.data.add_price = result.data.activity.add_price || cart.data.add_price; //加价购数据

        var tempData = result.data.activity || {};
        if(result.data.sub_products != '') {
            tempData.sub_products = result.data.sub_products;
        }

        if(result.data.activity == '' && result.data.sub_products == '') {
            cart.data.activity = '';
        } else {
            cart.data.activity = tempData;
        }

        cart_group.groupWeiXinPlay(); //团购是否显示微信支付;
        actives.cart = base.resetArr(result.data.product,'id');
        actives.subProduct = base.resetArr(result.data.sub_products,'pid');
        cart.data.sub_products = result.data.sub_products;

        /*cart 重购优化,2016-08-23号上,如无误，可以删除
        if(user.userBase.league_id != _activesSwitch) { //活动测试调试
            show_activty_tip(result);
        } else {
            var tempData = result.data.activity || {};
            if(result.data.sub_products != '') {
                tempData.sub_products = result.data.sub_products;
            }

            if(result.data.activity == '' && result.data.sub_products == '') {
                cart.data.activity = '';
            } else {
                cart.data.activity = tempData;
            }

            cart_group.groupWeiXinPlay(); //团购是否显示微信支付;
            actives.cart = base.resetArr(result.data.product,'id');
            actives.subProduct = base.resetArr(result.data.sub_products,'pid');
            cart.data.sub_products = result.data.sub_products;
        } */

        //如果存在默认地址
        if (result.data.default_address!=undefined && result.data.default_address!="" && result.data.default_address.address != "请选择收货地址"){
            var addressData = null;
            if(common.isFendian()){
                addressData = user.userBase.default_address;
            }else{
                addressData = result.data.default_address;
            }
            user_address.show_in_cart(addressData,0,0);
        }

        // if(result.data.Timing == 1 && cart.data.cart_type != 2) { //定时达是否开启
        //     $('#timing_btn').show();
        // }

        //支付方式开关
        var locationSwitch = $.inArray('0',result.data.paySwitch);
        var weixinSwitch = $.inArray('1',result.data.paySwitch);
        var alipaySwitch = $.inArray('2',result.data.paySwitch);
        if(locationSwitch < 0){
            //关闭货到付款
            $('#location-pay').hide();
            //如果开启了微信支付
            if(weixinSwitch >= 0){
                $('#pay_type1').click();
            }else{
                $('#pay_type2').click();
            }
        }
        if(weixinSwitch < 0){
            //关闭微信支付
            $('#weixin-pay').hide();
        }
        if(alipaySwitch < 0){
            //关闭支付宝支付
            $('#alipay-pay').hide();
        }

        if(cart.data.packbag != '') {
            /*
             if(_minAutumnSwitch == 1 ) {
             mid_autumn.createBagTpl(cart.data);
             } else {
             cart_bag.create_data(cart.data);
             }
             */
            mid_autumn.createBagTpl(cart.data);
            cart_bag.create_data(cart.data);
        }

        if(_minAutumnSwitch == 1) {
            mid_autumn.init();
        }

        actives.addPriceControl(cart.data.add_price);
        common.renderTpl("#cart-sub-products","./cart/cart_sub_products",{data: result.data.sub_products});

        noutoasiakas.init_config(result.data.ziti);//自提地址数据配置
        cart.blance_init(result.data.blance_money); //用户余额初始化
        cart.add_product_cart = { cart:{}, total: 0, selected:0 }; //用户加价购购物车

        cart.count_show(0,0,"");
    }});
}

var noutoasiakas = {}; //自提函数集
/*初始化自提显示数据*/
noutoasiakas.init_config = function(data) {
    if(data == undefined || data == ""){
        return false;
    }
    if(common.isFendian()){
        //配送店
        $("#send_btn").show();
        return false;
    }
    if(common.isZiti() || common.isBingoBox()){
        //自提点或缤果盒子
        $("#ziti_btn").show();
        $("#send_btn").hide();
        $('input[name="send_type"]:checked').val(2);
        $('#ziti_btn').find('label.round').addClass('current');
        cart.select_send_type(2); //设置自提送货时间
        $("#ziti_addr").text(user.userBase.display_name);
        $('#ziti_address').text(data.abholung_address);
        if(data.ser_tel) {
            $("#ziti_addr_tel").text('联系电话：'+data.ser_tel);
        }
        $('.abholung-position-wrap h3').html(user.userBase.display_name);
        $('.abholung-position-inner div img').attr('src',data.abholung_img);
        return false;
    }

    if (data.is_abholung == 1){ //开启自提功能
        $("#ziti_btn").show();
    }

    if(data.only == 1){
        //只开自提
        cart.ziti_only = 1;
        $("#send_btn").hide();
        $('input[name="send_type"]:checked').val(2);
        $('#ziti_btn').find('label.round').addClass('current');
        cart.select_send_type(2); //设置自提送货时间
    } else {
        $("#send_btn").show();
    }
    $("#ziti_addr").text(data.abholung_address);
    if(data.ser_tel) {
        $("#ziti_addr_tel").text('联系电话：'+data.ser_tel);
    }
    $('.abholung-position-wrap h3').html(data.abholung_address);
    $('.abholung-position-inner div img').attr('src',data.abholung_img);

}

/*获得活动信息*/
cart.get_active_info = function(){
    var url=api_host+"/Api/Buycar/car";
    var openid=user.userBase.bingo_openid;

    if (openid==undefined || openid==null || openid.length==0){
        return false;
    }
    /*
    var buycar = getCookie('buycar');
    buycar = product_weighing.buycartAddWeights(buycar);

    var special_car = getCookie('special_car');
    var product_type = cart.get_product_type();
    if(product_type != 'groupbuy' && product_type != 'special' && product_type != 'package' ) {
        if(buycar != null || product_weighing.productData.length > 0) {
            product_type = 'normal';
        }
        if(special_car != null ) {
            product_type = 'special';
        }
        if(buycar != null && special_car != null ) {
            product_type = 'blend';
        }
    }*/

    var cartBase = cart.getCartBaseInfo();
    /*
    var data={
        bingo_access_token:openid
        ,bingo_openid:openid
        ,product_type:cart.get_product_type()
        ,buycar:buycar
        ,voucher_id:cart.data.voucher.selected
        ,app_id:config.appid
        ,pay_type:cart.getPayMethod()
    };*/

    var data={
        bingo_access_token:openid
        ,bingo_openid:openid
        ,product_type:cartBase.product_type
        ,buycar:cartBase.buycar
        ,sp_buycar:cartBase.special_car
        ,voucher_id:cart.data.voucher.selected
        ,app_id:config.appid
        ,pay_type:cart.getPayMethod()
        ,is_vip:common.isVip()? 1 : 0
    };

    $.ajax({type:'post',url:url,data:data,dataType: 'json',async:false,success:function(result) {
        if(result.status == "-08001"){
            $("#orderSubmit_btn").css('background','#CCC').removeAttr('onclick');
            tipsBox.createAlertBox(result.data);
            return false;
        }

        //actives.user_join_box = 0;
        //$('#cart-add-products-wrap').hide();
        if(result.status != 1){
            $("#orderSubmit_btn").css('background','#CCC').removeAttr('onclick');
            return false;
        }

        cart.data.cart_user_league = user.userBase.league_id; //临时数据
        cart.bag_skus = result.data.bag_skus;

        show_activty_tip(result);
        cart.data.sub_products = result.data.sub_products;



        var sub_product_tips = '';
        for(var i=0; i < result.data.sub_products.length; i++) {
            sub_product_tips += result.data.sub_products[i]['subtitle']+"<br/>";
        }
        if(sub_product_tips != '') {
            actives.user_join_box = 1;
            $('#user-join-actives').show();
            $('#sub_product_tips').data('info',sub_product_tips);
            $('#sub_product_tips').css('display','block');
            $('#cart-add-products-wrap').show();
        } else {
            $('#sub_product_tips').hide();
        }

        cart_group.groupWeiXinPlay();
        cart.show_sub_product(result.data.sub_products);
        actives.tipsControl();
    }});
}





cart.show_sub_product=function(sub_products){
    var tmp_array=[];
    for (var i=0;i<sub_products.length;i++){
        tmp_array.push(parseInt(sub_products[i]["id"]));
    }
    $(".sub_product").each(function(){
        var tmp_id=$(this).data("id");
        if (tmp_array.indexOf(tmp_id)==-1){
            $(this).remove();
            cart.sub_product_cart = {};
            cart.sub_product_total = 0;
        }
    });
}
cart.returnBtn = function() {
    config.cart_init();
    if( cart_group.order_come_from == 1 ) {
        cart_group.line = 0;
        cart_group.order_come_from = 0;
        window.location.href = '#/home';
        return false;
    }
    window.history.back()
}
/*显示活动提示*/
function show_activty_tip(result){
    if(result.status != 1) {
        return false;
    }

    $('.cart-add-products').hide();
    if(actives.user_join_box != 1) {
        actives.user_join_box = 0;
    }

    if( result.data.activity.BuyNGetOne != undefined && result.data.activity.BuyNGetOne != '' ) {
        actives.user_join_box = 1;
        $('#BuyNGetOne').css('display','block');
        $('#BuyNGetOne').html(result.data.activity.BuyNGetOne.event_name);
        $('#BuyNGetOne').data('info',result.data.activity.BuyNGetOne.remark);
        $('#BuyNGetOne').data('save',result.data.activity.BuyNGetOne.save);
        if(parseFloat(result.data.activity.BuyNGetOne.save) > 0) {
            $('#BuyNGetOne').addClass('BuyNGetOne-join-current');
        } else {
            $('#BuyNGetOne').removeClass('BuyNGetOne-join-current');
        }
    } else {
        $('#BuyNGetOne').hide();
    }

    if(result.data.activity.man_x_jian_y != undefined &&  result.data.activity.man_x_jian_y != ''  ) {
        actives.user_join_box = 1;
        $('#man_x_jian_y').css('display','block');
        $('#man_x_jian_y').html(result.data.activity.man_x_jian_y.event_name);
        $('#man_x_jian_y').data('info',result.data.activity.man_x_jian_y.remark);
        $('#man_x_jian_y').data('save',result.data.activity.man_x_jian_y.save);
        if(parseInt(result.data.activity.man_x_jian_y.save) == 0) {
            $('#man_x_jian_y').removeClass('man_x_jian_y-join-current');
        } else {
            $('#man_x_jian_y').addClass('man_x_jian_y-join-current');
        }
    } else {
        $('#man_x_jian_y').hide();
    }

    if(result.data.activity.discount_activity != undefined &&  result.data.activity.discount_activity != ''  ) {
        actives.user_join_box = 1;
        $('#discount_activity').removeClass('discount_activity-join-current');
        $('#discount_activity').css('display','block');
        $('#discount_activity').html(result.data.activity.discount_activity.event_name);
        $('#discount_activity').data('info',result.data.activity.discount_activity.remark);
        $('#discount_activity').data('save',result.data.activity.discount_activity.save);
        $('#discount_activity').data('old_save',result.data.activity.discount_activity.save);
        $('#discount_activity').data('pay',result.data.activity.discount_activity.pay_type);
        if(result.data.activity.discount_activity.pay_type == '') {
            if(result.data.activity.discount_activity.status == 1) {
                $('#discount_activity').addClass('discount_activity-join-current');
            } else {
                $('#discount_activity').removeClass('discount_activity-join-current');
            }
        } else  {
            cart.discount_activity(result);
        }
    } else {
        $('#discount_activity').hide();
    }

    if(result.data.activity.man_x_give_voucher != undefined &&  result.data.activity.man_x_give_voucher != ''  ) {
        actives.user_join_box = 1;
        $('#man_x_give_voucher').css('display','block');
        $('#man_x_give_voucher').html(result.data.activity.man_x_give_voucher.event_name);
        $('#man_x_give_voucher').data('info',result.data.activity.man_x_give_voucher.remark);
        if(parseInt(result.data.activity.man_x_give_voucher.is_give) == 0) {
            $('#man_x_give_voucher').removeClass('man_x_give_voucher-current');
        } else {
            $('#man_x_give_voucher').addClass('man_x_give_voucher-current');
        }
    } else {
        $('#man_x_give_voucher').hide();
    }

    if(result.data.activity.N_bei_points != undefined && result.data.activity.N_bei_points != ''){
        actives.user_join_box = 1;
        $('#N_bei_points').css('display','block');
        $('#N_bei_points').html(result.data.activity.N_bei_points.event_name);
        $('#N_bei_points').data('info',result.data.activity.N_bei_points.remark);
        $('#N_bei_points').addClass('N_bei_points-current');
    } else {
        $('#N_bei_points').hide();
    }

    if(actives.user_join_box == 1) {
        $('.user-join-actives').show();
        $('.shopping-bag-select-btn').addClass('shopping-bag-select-activeing');
    } else {
        $('.user-join-actives').hide();
        $('.shopping-bag-select-btn').removeClass('shopping-bag-select-activeing');
    }
}

cart.discount_activity = function(result) {
    var discount_activity_status = 0;
    var save = $('#discount_activity').data('old_save');
    var pay_type = $("input[name='pay_type']:checked").val();
    var pay_type_list = result.data.activity.discount_activity.pay_type;
    pay_type_list = pay_type_list.split(',');
    if(save > 0) {
        for (var i in pay_type_list) {
            if (pay_type_list[i] == pay_type) {
                discount_activity_status = 1;
                cart.data.online_discount_pay = 1;
                $('#discount_activity').data('save', save);
                $('#discount_activity').addClass('discount_activity-join-current');
            }
            if (discount_activity_status == 0) {
                cart.data.online_discount_pay = 0;
                $('#discount_activity').data('save', 0);
                $('#discount_activity').removeClass('discount_activity-join-current');
            }
        }
    }

    /* 屏蔽支付打折提示
    if(result.data.activity.discount_activity.order_discount !='' && result.data.activity.discount_activity.order_discount != undefined) {
        for (var i in pay_type_list) {
            $('#pay_type' + pay_type_list[i]).parent().find('span.weixin_discout').html(result.data.activity.discount_activity.order_discount + '折');
            $('#pay_type' + pay_type_list[i]).parent().find('span.weixin_discout').css('display', 'inherit');
        }
    }*/
}

/*送货方式切换*/
cart.select_send_type=function(type){
    var sendTips = $('#select-time-title').html();
    if (type==1){       //普通送货
        $("#ziti_addr_div").hide();
        $('#address-manage').show();
        $('#timing-fee').hide();
        $('#send_name').html('收货<br>时间');
        $('#select-time-title').html('请选择收货时间');
        $('#ziti_tel_wrap').hide();
        $('#select-time-p').attr('onclick','showDeliveryTime()');
        cart.render_sendTime(cart.get_product_type(),cart.user_receive_time);
    }else if (type==2){         //自提
        $("#ziti_addr_div").show();
        $('#address-manage').hide();
        $('#timing-fee').hide();
        $('#send_name').html('自提<br>时间');
        $('#select-time-title').html('请选择自提时间');
        $('#ziti_tel_wrap').show();
        $('#select-time-p').attr('onclick','showDeliveryTime()');
        get_zitiTime();
    }else if(type==3){           //定时达
        tipsBox.createAlertBox("你选择了缤果<span class=\"textComColor\">【定时达】</span>服务，你可以指定某个时间将产品准时送达，但需收<span class=\"textComColor\">" + cart.timing_cost + "元服务费</span>。若超过指定时间<span class=\"textComColor\">" + cart.timing_timeout + "分钟</span>未送达，将退回" + cart.timing_cost + "元服务费到你的余额，并赠送你<span class=\"textComColor\">"+ cart.timing_voucher +"</span>致歉");
        $("#ziti_addr_div").hide();
        $('#address-manage').show();
        $('#timing-fee').show();
        $('#send_name').html('收货<br>时间');
        $('#select-time-title').html('请选择定时达收货时间');
        $('#ziti_tel_wrap').hide();
        $('#select-time-p').attr('onclick','cart.showTimingTime()');
        cart.render_timing();
    }
    $("#reciveTime").val('');
    $("#forwardTime").val('');
    $('#forwardTime_s').val('');

    mid_autumn.sendMothed(0)
    cart.count_show(0,0,"");
};
/*显示定时达时间*/
cart.showTimingTime = function(){
    $("html,body").css("overflow","hidden");
    $('#select-model-timing').show();
    $('.select-time-mask').show();
    var liLength = $('.timing-dateday li').length;
    $('.timing-item-switch').css('width', parseFloat($('.timing-item-switch-box').width()) * liLength + 'px');
    $('.timing-datetime').css('width',$('.timing-item-switch-box').width() + 'px');
}
/*隐藏定时达时间*/
cart.hideTimingTime = function(){
    $("html,body").css("overflow","");
    $('#select-model-timing').hide();
    $('.select-time-mask').hide();
}

cart.getPayMethod = function() {
    var pay_type = $("input[name='pay_type']:checked").val() || 0;
    return pay_type;
}


/*定时达时间计算*/
Date.prototype.DateAdd = function(strInterval, Number) {
    var dtTmp = this;
    switch (strInterval) {
        case 's' :return new Date(Date.parse(dtTmp) + (1000 * Number));
        case 'n' :return new Date(Date.parse(dtTmp) + (60000 * Number));
        case 'h' :return new Date(Date.parse(dtTmp) + (3600000 * Number));
        case 'd' :return new Date(Date.parse(dtTmp) + (86400000 * Number));
        case 'w' :return new Date(Date.parse(dtTmp) + ((86400000 * 7) * Number));
        case 'q' :return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number*3, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
        case 'm' :return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
        case 'y' :return new Date((dtTmp.getFullYear() + Number), dtTmp.getMonth(), dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
    }
}
/*获取年月*/
cart.getDateStr = function(AddDayCount) {
    var dd = new Date();
    dd.setDate(dd.getDate()+AddDayCount);//获取AddDayCount天后的日期
    var y = dd.getFullYear();
    var m = dd.getMonth() + 1;
    return y + "-" + m;
}
/*渲染定时达时间*/
var to_ym = "";    //年份
var today_first_hour_status = 0;  //是否选了今天的第一个小时0为否，1为是
cart.render_timing = function(){

    var html = template('cart_timingTime');
    $('#select-model-timing').html(html);

    $('#timing_send_voucher').text(cart.timing_voucher);    //赔付的代金券
    $('#timing_timeout').text(cart.timing_timeout);    //赔付的代金券
    $('#timing_cost').text(cart.timing_cost);    //定时达运费

    var myDate = new Date();

    var today_m = myDate.getMonth() + 1;    //今天的月
    var today_d = myDate.getDate();         //今天的日
    var tomo_m = myDate.DateAdd("d",1).getMonth() + 1;      //明天的月
    var tomo_d = myDate.DateAdd("d",1).getDate();           //明天的日
    if(parseInt(today_m) < 10){
        today_m = "0" + today_m;
    }
    if(parseInt(today_d) < 10){
        today_d = "0" + today_d;
    }
    if(parseInt(tomo_m) < 10){
        tomo_m = "0" + tomo_m;
    }
    if(parseInt(tomo_d) < 10){
        tomo_d = "0" + tomo_d;
    }
    var t1 = today_m + "-" + today_d;//今天12-25
    var t2 = tomo_m + "-" + tomo_d;//明天12-26
    var tt1 = myDate.getDate();
    var tt2 = myDate.DateAdd("d",1).getDate();

    $('#timing_date_day').val(tt1 + "日"); //先保存今天的日期
    $("#timeing_t1").attr("onclick","cart.show_timing_day(0,'" + tt1 + "')");
    $("#timeing_t2").attr("onclick","cart.show_timing_day(1,'" + tt2 + "')");
    $("#timeing_t1").html(t1 + "今天");
    $("#timeing_t2").html(t2 + "明天");

    var timingDate = cart.user_receive_time.sendTime;

    var unsend_time_list = []; //所有运力已满时间
    var today_st = ""; //今天的开始时间
    var today_et = ""; //今天的结束时间
    var tomo_st = ""; //明天的开始时间
    var tomo_et = ""; //明天的结束时间

    //今天的年份
    to_ym = cart.getDateStr(0);

    for (var i = 0; i < timingDate.length; i++){
        var tmp_t = timingDate[i];
        if (tmp_t["day"] != t1 && tmp_t["day"] != t2){
            continue;
        }
        var tmp_d = timingDate[i].data;
        //已经过去的时间不会出现
        for (var x = 0; x < tmp_d.length; x++){
            if(today_st == "" && tmp_t["day"] == t1 && tmp_d[x]["allow"] == "1"){
                today_st = myDate.getFullYear() + "-" + tmp_t["day"] + " " + tmp_d[x]["earliest_time"] + ":00";
            }
            //今天的结束时间
            if ( tmp_t["day"] == t1 && tmp_d[x]["allow"] == "1"){
                today_et = myDate.getFullYear() + "-" + tmp_t["day"] + " " + tmp_d[x]["last_time"] + ":00";
            }
            //明天的开始时间
            if ( tomo_st == "" && tmp_t["day"] == t2 && tmp_d[x]["allow"] == "1"){
                tomo_st = myDate.getFullYear() + "-" + tmp_t["day"] + " " + tmp_d[x]["earliest_time"] + ":00";
            }
            //明天的结束时间
            if ( tmp_t["day"] == t2 && tmp_d[x]["allow"] == "1"){
                tomo_et = myDate.getFullYear() + "-" + tmp_t["day"] + " " + tmp_d[x]["last_time"] + ":00";
            }
            //运力已满的时间
            if (tmp_d[x]["allow"] == "-1"){
                var u_str = myDate.getFullYear() + "-" + tmp_t["day"] + " " + tmp_d[x]["last_time"] + ":00";
                var u1 = new Date(u_str.replace(/-/g,"/"));
                var h1 = u1.DateAdd("h",-1); //前一小时
                var h2 = u1.DateAdd("h",-2); //前2小时
                unsend_time_list.push(common.dateFormat(h1,"yyyy-M-d h:m:s"));
                unsend_time_list.push(common.dateFormat(h2,"yyyy-M-d h:m:s"));
            }
        }
    }
    //今天的第一个时间需要判断分钟
    if (today_st != "" && today_et != ""){     //今天
        var x1 = (new Date(today_st.replace(/-/g,"/")).getHours()); //开始
        var x2 = (new Date(today_et.replace(/-/g,"/")).getHours()); //结束
        $("#timeing_hour1").html("");
        for (var xx = x1 + 1; xx < x2; xx++){
            var tmp_id = (new Date(today_st.replace(/-/g,"/")).getDay()) + "-" + xx;
            if(xx == x1){
                var html = "<dd><a href=\"javascript:void(0);\" id=\"" + tmp_id + "\" onclick=\"cart.timing_hms('first_hour'," + xx + ")\">" + xx + "时</a></dd>";
            }else{
                var html = "<dd><a href=\"javascript:void(0);\" id=\"" + tmp_id + "\" onclick=\"cart.timing_hms('hour'," + xx + ")\">" + xx + "时</a></dd>";
            }
            $("#timeing_hour1").append(html);
        }
    }else{
        //今天没有可选时间
        $("#timing-item-0").html("<p>今天已结束啦</p>");
    }

    if (tomo_st != "" && tomo_et != ""){     //明天
        var x1 = (new Date(tomo_st.replace(/-/g,"/")).getHours()); //开始
        var x2 = (new Date(tomo_et.replace(/-/g,"/")).getHours()); //结束
         $("#timeing_hour2").html("");
        for (var xx = x1 + 1; xx < x2; xx++){
            var tmp_id = (new Date(tomo_st.replace(/-/g,"/")).getDay()) + "-" + xx;
            var html = "<dd><a href=\"javascript:void(0);\" id=\"" + tmp_id + "\" onclick=\"cart.timing_hms('hour'," + xx + ")\">" + xx + "时</a></dd>";
            $("#timeing_hour2").append(html);
        }
    }else{
        //明天没有时间可选
        $("#timing-item-1").html("<p>今天已结束啦</p>");
    }

    //两天的排除时间不可选
    for (var a = 0; a < unsend_time_list.length; a++){
        var tmp_data = (new Date(unsend_time_list[a].replace(/-/g,"/")));
        var tmp_day_id = tmp_data.getDay() + "-" + tmp_data.getHours(); //25-10
        $("#"+tmp_day_id).addClass('onactive');
        $("#"+tmp_day_id).attr('onclick',"cart.sendTimeForbidden(-1)");    //运力已满
    }
}
/*字符串时间转化为时间戳*/
// function get_unix_time(dateStr){
//     var newstr = dateStr.replace(/-/g,'/');
//     var date =  new Date(newstr);
//     var time_str = date.getTime().toString();
//     return time_str.substr(0, 10);
// }
/*提交定时达时间*/
var timing_stringtime = "";   //定时达时间
cart.submit_timing = function(){
    var timing_h = $('#timing-h').text();
    var timing_m = $('#timing-m').text();
    if(timing_h == 0){
        tipsBox.createAlertBox("请选择正确的定时达收货时间，滚动时分秒后点击选择适合您的时间！");
        return false;
    }
    var timing_day = $('#timing_date_day').val();
    var str = timing_day + timing_h + '时' + timing_m + '分定时达';
    timing_stringtime = to_ym + "-" + timing_day.replace("日","") + " " + timing_h + ":" + timing_m + ':00';
    var timing_timestamp = base.getUnixTime(timing_stringtime);
    $('#forwardTime').val(timing_timestamp);   //保存时间戳

    $("#select-time-title").text(str);
    $("#reciveTime").val(str);
    cart.hideTimingTime();
}
/*选择时分秒*/
cart.timing_hms = function(type,time){
    if(type == "hour"){     //小时
        $("#timing-h").text(time);
        //如果上一个选择的小时是今天的第一个小时，重新渲染分钟
        if(today_first_hour_status == 1){
            cart.timing_minute();
        }
    }else if(type == "minute"){     //分
        $("#timing-m").text(time);
    }else if(type == "first_hour"){    //今天的第一个小时
        $("#timing-h").text(time);
        cart.timing_first_hour(time);
    }
}
/*选择今天的第一个小时，重新渲染分钟，已过去的分钟不能再选*/
cart.timing_first_hour = function(time){
    today_first_hour_status = 1;
    $("#timeing_hour1_minute").html("");    //清空
    var myDate = new Date();
    var now_minute = myDate.getMinutes();

    for(var i = 0; i < 60; i++){
        if(i<10){
            var j = "0" + i;
        }else{
            var j = i;
        }
        if(i <= now_minute){    //小于当前分钟不可选
            var html = "<dd><a href=\"javascript:void(0);\" class=\"onactive\" onclick=\"cart.sendTimeForbidden(0)\">" + j + "分</a></dd>";
        }else{
            var html = "<dd><a href=\"javascript:void(0);\" onclick=\"cart.timing_hms('minute'," + j + ")\">" + j + "分</a></dd>";
        }
        $("#timeing_hour1_minute").append(html);
    }
}
/*重新渲染所有分钟*/
cart.timing_minute = function(){
    today_first_hour_status = 0;
    $("#timeing_hour1_minute").html("");    //清空
    var j = 0;
    for(var i = 0; i < 60; i += 10){
        if(i<10){
            j = "0" + i;
        }else{
            j = i;
        }
        var html = "<dd><a href=\"javascript:void(0);\" onclick=\"cart.timing_hms('minute'," + j + ")\">" + j + "分</a></dd>";
        $("#timeing_hour1_minute").append(html);
    }
}
/*日期差计算*/
cart.timing_comptime = function(timing_time,now_time) {
    var beginTimes = timing_time.substring(0, 10).split('-');
    var endTimes = now_time.substring(0, 10).split('-');

    beginTime = beginTimes[1] + '-' + beginTimes[2] + '-' + beginTimes[0] + ' ' + timing_time.substring(10, 19);
    endTime = endTimes[1] + '-' + endTimes[2] + '-' + endTimes[0] + ' ' + now_time.substring(10, 19);

    // var a = (Date.parse(beginTime) - Date.parse(endTime)) / 3600 / 1000;
    var b = (Date.parse(beginTime) - Date.parse(endTime)) / 1000;;
    if(b < 3300){  //超过5分钟
        return 0;
    }else{
        return 1;
    }
}
/*定时达日期切换*/
cart.show_timing_day = function(num,text){
    if(num == 0){
        to_ym = cart.getDateStr(0); //今天的年份
    }else{
        to_ym = cart.getDateStr(1); //明天的年份
    }
    $('#timing_date_day').val(text + "日");     //保存日期
    //清空时分
    if(!$('.timing-dateday li').eq(num).find('a').hasClass('onactive')){
        $("#timing-h").text(0);
        $("#timing-m").text(0);
    }

    $('.timing-dateday li').find('a').removeClass("onactive");
    $('.timing-dateday li').eq(num).find('a').addClass("onactive");

    var conInnerConWidth = $(".timing-item-switch-box").width();//每项宽度
    $(".timing-item-switch").animate({marginLeft:-num*conInnerConWidth+"px"});

}

/*计算团购费用*/
cart.count_group=function(){
    cart.data.product_list=[];
    var total_fee = 0;
    var buycar = getCookie('buycar');
    if(buycar != null) {
        var all_p = buycar.split("|");
        if(all_p.length > 0 && all_p[0] != "") {
            cart.data.all_num=0;
            for (var i = 0; i < all_p.length; i++) {
                var p = all_p[i].split(',');
                var id=p[0];
                var product=product_group_list[id];
                if (product!=undefined){
                    cart.data.all_num+=1;
                    total_fee+=(product.price);

                    cart.data.product_list.push(product);
                }

            }
        }
    }

    //如果超过设置，扣减运费
    /*
    if (parseFloat(cart.data.AddrVo.fee_free)>parseFloat(total_fee)){
        cart.data.dev_fee=cart.data.AddrVo.fee;
    }else{
        cart.data.dev_fee=0;
    }*/

    cart.data.dev_fee = 0;
    if(id != undefined) {
        if(product_group_list[id]['B_yunfei'] == 1) {
            cart.data.dev_fee = parseFloat(product_group_list[id]['groupbuy_yunfei']);
        }
    }
    cart.data.groupbuy_fee = cart.data.dev_fee;
    cart.data.last_total_fee=(parseFloat(total_fee)+parseFloat(cart.data.dev_fee)-parseFloat(cart.data.lower_fee)-parseFloat(cart.data.voucher_fee)).toFixed(2);
};

/*计算费用*/
cart.count = function() {
    /*cart 重购优化,2016-08-23号上,如无误，可以删除
    if(user.userBase.league_id == _activesSwitch) {
        actives.init(cart.data.activity);
    } else {
        cart.get_active_info();
    }*/

    actives.init(cart.data.activity);
    cart.data.all_num = 0;
    cart.data.product_list = [];
    var total_fee = 0;
    var active_save = 0;
    var allow_voucher_num = 0;
    var disallow_voucher_num = 0;
    var disallow_voucher_fee = 0;
    var disallow_voucher_tips = '';
    var buycar = getCookie('buycar');
    if(buycar != null) {
        var all_p = buycar.split("|");

        if(all_p.length > 0 && all_p[0] != "") {
            //cart.data.all_num=0;
            for (var i = 0; i < all_p.length; i++) {
                var p = all_p[i].split(',');
                var id=p[0];
                var product;
                if (cart.data.cart_type==2){
                    product=product_group_list[id];
                }else if (cart.data.cart_type==1){
                    product=product_special_list[id];
                }else if (cart.data.cart_type==3){
                    product=product_package_list[id];
                }
                else{
                    product=product_list[id]
                }
                if (product != undefined){
                    allow_voucher_num += 1;
                    cart.data.all_num += product.num;
                    total_fee += (product.price * product.num);
                    cart.data.product_list.push(product);
                    if(product.allow_voucher != 1) {
                        disallow_voucher_num += 1;
                        disallow_voucher_fee += (product.price * product.num);
                        disallow_voucher_tips += product.title + ","
                    }
                }

            }
        }
    }

    // 如果存在称重产品，加上称重产品价格
    var data = product_weighing.productData;
    if(data.length > 0){
        for(var i = 0; i < data.length; i++){
            allow_voucher_num++;
            cart.data.all_num++;
            total_fee += parseFloat(data[i].price);
            if(data[i].allow_voucher != 1){
                disallow_voucher_fee += parseFloat(data[i].price);
                disallow_voucher_num++;
            }
        }
    }

    cart.disallow_voucher_fee = disallow_voucher_fee;
    cart.disallow_voucher_status = (allow_voucher_num == disallow_voucher_num) ? 1 : 0;
    if(cart.disallow_voucher_fee != 0 || cart.disallow_voucher_status == 1) {
        cart.disallow_voucher_tips = "该优惠券不符合使用条件!注："+disallow_voucher_tips+"不允许使用优惠卷。";
    }
    cart.fruit_total = total_fee;


    cart.special_count();
    cart.data.all_num = cart.data.all_num + cart.data.special_all_num;
    cart.data.man_x_jian_y_fee = parseFloat($('#man_x_jian_y').data('save')) >= 0 ? parseFloat($('#man_x_jian_y').data('save')) : 0;
    cart.data.BuyNGetOne_fee = parseFloat($('#BuyNGetOne').data('save')) >= 0 ? parseFloat($('#BuyNGetOne').data('save')) : 0;
    cart.data.discount_activity_fee=parseFloat($('#discount_activity').data('save')) >= 0 ? parseFloat($('#discount_activity').data('save')) : 0;
    cart.data.last_total_fee = cart.order_sum();
    cart.data.last_total_fee -= actives.addProductCount(); //加价购不满足时特别处理

    if(cart.data.all_num == 0) {
        $('#cart_no_fruit').show();
        $('.shopping-box').hide();
    } else {
        $('#cart_no_fruit').hide();
        $('.shopping-box').show();
    }
    if(cart.data.special_all_num == 0) { //不显示特价商品
        $('.cart-special-fruit-box').hide();
    }

    if(cart.data.special_all_num >= 1 && cart.data.all_num - cart.data.special_all_num >= 1 ) {
        $('.normal-product-box li:last-child').css('borderWidth','1px');
    }
};
/*计算抢购水果费用*/
cart.special_count = function() {
    cart.data.special_list = [];
    var special_all_num = 0;
    var special_total_fee = 0;
    var special_car = getCookie('special_car');
    if(special_car != null) {
        var all_p = special_car.split("|");
        if(all_p.length > 0 && all_p[0] != "") {
            for (var i = 0; i < all_p.length; i++) {
                var p = all_p[i].split(',');
                var product = product_special_list[p[0]];
                if (product!=undefined){
                    special_all_num += product.num;
                    special_total_fee += (product.price * product.num);
                    cart.data.special_list.push(product);
                }
            }
        }
    }
    cart.data.special_all_num = special_all_num;
    cart.special_fruit_total = special_total_fee;
}
/*统计订单最后的应付价钱*/
cart.order_sum = function() {
    var total = 0;
    total += parseFloat(cart.fruit_total); //购买水果应支付费用
    total += parseFloat(cart.special_fruit_total); //购买特价水果应支付费用
    total += parseFloat(cart.data.bags_fee); //环保袋支付费用
    //total += parseFloat(cart.data.add_price_product.price);//加价购，兑换指定水果金额
    total += parseFloat(cart.add_product_cart.total);//加价购，兑换指定水果金额
    total += parseFloat(cart.sub_product_total); //加价购，兑换子产品金额
    total += parseFloat(cart_bag.price); //购物袋，购物带需要金额
    total -= parseFloat(cart.data.man_x_jian_y_fee); //满x减y，优惠金额
    total -= parseFloat(cart.data.discount_activity_fee); //折扣活动优惠
    total -= parseFloat(cart.data.BuyNGetOne_fee); //买N兔一,优惠金额
    total -= parseFloat(cart.data.lower_fee); //减免金额
    total += cart.order_fee_free(total);//运费金额
    total -= parseFloat(cart.data.voucher_fee); //用户使用优惠券减免金额
    total += cart.timing_fee(total);  //定时达费用

    return total.toFixed(2);
}
/*定时达运费*/
cart.timing_fee = function(total){
    if($('input[name="send_type"]:checked').val() != 3){    //没选中返回0
        return parseFloat(0);
    }else{
        return parseFloat(cart.timing_cost);
    }
}
/*统计订单排除运费和排除优惠券*/
cart.order_fruit_sum = function() {
    var total = 0;
    total += parseFloat(cart.data.last_total_fee); //订单最终应支付金额
    total += parseFloat(cart.data.voucher_fee); //用户使用优惠券减免金额
    total -= parseFloat(cart.data.dev_fee);//运费金额
    return total;
}
/*如果超过设置，扣减运费*/
cart.order_fee_free = function(total){
    cart.data.dev_fee = 0;
    if (cart.order_count<=0){ //首单免运费
        actives.user_join_box = 1;
        $('.user-join-actives').show();
        $('#first-order-btn').data('info',"新用户首单免运费，已经为您减免"+cart.data.AddrVo.fee+"元");
        $('#first-order-btn').css('display','block');
        return parseFloat(cart.data.dev_fee);
    }

    if(parseFloat(cart.data.AddrVo.fee_free) > parseFloat(total)){ //正常水果计算运费方式
        var send_type = $('input[name="send_type"]:checked').val();
        cart.data.dev_fee = (send_type == 2) ? 0 : cart.data.AddrVo.fee;
    } else {
        cart.data.dev_fee = 0;
    }

    if(cart.data.cart_type == 2) { //团购计算运费方式
        var send_type = $('input[name="send_type"]:checked').val();
        cart.data.dev_fee = (send_type == 2) ? 0 : cart.data.groupbuy_fee;
    }

    if($('input[name="send_type"]:checked').val() == 3){
        cart.data.dev_fee = 0;
    }

    if(common.isZiti() || common.isBingoBox()){
        //自提点或盒子免运费
        cart.data.dev_fee = 0;
    }

    return parseFloat(cart.data.dev_fee);
}
/*删除一个产品*/
cart.del_item = function(id){
   tipsBox.createConfirmBox('您确定将这款商品从购物车里删除吗？','cart.sure_del_item',id,'确定');
};
/*删除抢购水果产品*/
cart.del_special_fruit = function(id) {
    tipsBox.createConfirmBox('您确定将这闪购商品从购物车里删除吗？','product_special.del_btn',id,'确定');
}

cart.sure_del_item = function(id){
    var buycar = getCookie('buycar');
    var all_p = buycar.split("|");
    product_list[id].num = 0;
    var p = product_list[id];
    operateCart(p);
    cart.count_show(id,p,"del");
    $("#goods-"+id).remove();
    tipsBox.hideTipsBox();
    if (all_p.length <= 1 && product_weighing.productData.length == 0){
        window.location.href="#/home";
    }
}
/*编辑购物车*/
var cartShopEdit_sattus=0;
function cartShopEdit(){
    var txt="编辑";
    if (cartShopEdit_sattus==0){
        cartShopEdit_sattus=1;
        txt="完成";
        $('.editCarShop_num').show();
        $('.subtotal_num_box').hide();

        //按钮点击统计
        common.buttonClikcStatistics("car","car_edit","编辑产品");
    }else{
        cartShopEdit_sattus=0;
        $('.editCarShop_num').hide();
        $('.subtotal_num_box').show();
    }
    $("#user-shopping-edit").text(txt);
}
/*购物车内货物数量增减*/
function cart_action(id,type){
    var p=product_list[id];
    if (cart.data.cart_type==3){
        p=product_package_list[id];
    }
    var ret=false;
    if (p.num==1 && type=="subtract"){
        cart.del_item(id);
        // return false;
    }

    if (type=="plus"){
        ret=do_plus(p);
    }else if(type=="subtract" && p.num != 1){
        ret=do_subtract(p);
    }
    if (!ret){
        return false;
    }
    cart.count_show(id,p,type);
}
/*重新统计费用*/
cart.count_show=function(id,p,type){
    //清空优惠券
    if (type!="add_voucher" && cart.data.voucher.selected!=0 && type!="add_price"){
        cart.voucher_select(cart.data.voucher.selected);
    }
    if (type!="") {
        // if (p.num == 1 && type == "subtract") {
        //     $("#minus_btn_" + id).addClass("forbidden1");
        // }
        // if (p.num >= 1 && type == "plus") {
        //     $("#minus_btn_" + id).removeClass("forbidden1");
        // }
        $(".subtotal_num_" + id).text(p.num);
        var price = (p.price * p.num).toFixed(2);
        $("#subtotal_price_" + id).text(price);
    }

    actives.add_price_status = (type!="add_price") ? 1 : 0;
    cart.count();

    //包装袋
    if((cart.data.all_num >= parseInt(cart.bag_skus) || cart_bag.id != 0) && cart_bag.bag_data != "") {
        $("#packaging-tips").show();
        $("#packaging-tips-2").show();

        var mid_gift = $('input[name="gifts"]:checked').val();
        if(mid_gift == 2) {
            $('.shopping-bag-select-btn').hide();
            $('#mid-autumn-bag').show();
        } else {
            $('#mid-autumn-bag').hide();
            $('.shopping-bag-select-btn').show();
        }
        /*
        if(_minAutumnSwitch == 1) {
         $('#mid-autumn-bag').show();
        } else {
            $('.shopping-bag-select-btn').show();
        }*/

        cart_bag.get_free_packbag(cart.data.packbag);
    } else {
        $("#packaging-tips").hide();
        $("#packaging-tips-2").hide();
        $('.shopping-bag-select-btn').hide();
        $('#mid-autumn-bag').hide();
    }

    if(cart.data.sub_products != '') {
        $('.add-price-model-2').show();
        $('.add-price-name-'+cart.data.sub_products[0].id).html('兑&nbsp;&nbsp;&nbsp;&nbsp;换：');
        if (cart.data.add_price !== "" ){
             $('.add-price-name').html('');
        }
    }

    /*cart 重购优化,2016-08-23号上,如无误，可以删除
    if(user.userBase.league_id != _activesSwitch) { //加价购
        if (type!="add_price") {
            cart.show_add_price();
        }
    }*/

    /*
    if(cart.data.add_price_product.id  != 0) {
        $('.add-price-selected').addClass('current');
        $('#add_price_div').addClass('add-price-join-current');
    } else {
        $('.add-price-selected').removeClass('current');
        $('#add_price_div').removeClass('add-price-join-current');
    }*/


    $("#all_num").text(cart.data.all_num);
    $("#all_num-2").text(cart.data.all_num);
    $("#bags").text(base.setNumberDecimals(cart.data.bags_fee));
    $("#packaging").text(base.setNumberDecimals(cart_bag.price));

    var html_total_price  = parseFloat(cart.data.last_total_fee) > 0 ? cart.data.last_total_fee : 0;
    html_total_price = base.setNumberDecimals(html_total_price);
    $("#totalPrice").text(html_total_price);
    cart.needPay(html_total_price);

    $("#totalPrice").data('totalPrice',html_total_price);
    $("#totalPrice-2").text(html_total_price);
    cart.get_remain_blance_money(html_total_price);
    $("#deliveryFeePrice").text(base.setNumberDecimals(cart.data.dev_fee));
    $("#deliveryFeePrice-2").text(base.setNumberDecimals(cart.data.dev_fee));
    $("#timingFee").text(base.setNumberDecimals(cart.timing_cost));     //定时达费用
    cart.setDeliveryTotalShow();


    var free_fee = base.setNumberDecimals(parseFloat(cart.data.lower_fee) + parseFloat(cart.data.voucher_fee) + cart.data.man_x_jian_y_fee + cart.data.BuyNGetOne_fee + cart.data.discount_activity_fee);

    $("#activeSave").text('- '+free_fee);
    $("#activeSave").data('save',free_fee);
    $("#activeSave-2").text('- '+free_fee);
    if(parseFloat(free_fee) > 0) {
        $("#activeSave-tips").show();
        $("#activeSave-tips-2").show();
    } else {
        $("#activeSave-tips").hide();
        $("#activeSave-tips-2").hide();
    }
    cart.setDeliveryTotalShow();
};

/**
 * 用户还需要支付
 * @method cart.needPay
 */
cart.needPay = function(price) {
    var car_blance_money = $('input[name="car_blance_money"]:checked').val();
    if(car_blance_money === '1') {
        if(parseFloat(cart.data.blance_money) >= parseFloat(price)) {
            price = 0;
        } else  {
            price = base.setNumberDecimals(parseFloat(price) - parseFloat(cart.data.blance_money));
        }
    }
    $('.cart-total em').html(price);
}

/**
 * 显示快递费用
 * @method cart.setDeliveryTotalShow
 */
cart.setDeliveryTotalShow = function() {
    var deliveryTotal = cart.data.dev_fee;
    var send_type = $('input[name="send_type"]:checked').val();
    if(send_type == 3) {
        deliveryTotal = cart.timing_cost;
    }
    if(parseFloat(deliveryTotal) > 0) {
        $('#delivery-total').html(base.setNumberDecimals(deliveryTotal));
        $('#delivery-total').parent().show();
    } else {
        $('#delivery-total').parent().hide();
    }
}

cart.blance_init = function(blance_money) {
    cart.data.blance_money = blance_money;
    $('#car_user_blance_money').html(base.setNumberDecimals(blance_money));

    if(parseFloat(cart.data.blance_money) > 0) {
        $('.blance-money-box').show();
        // $('#car_blance_money').attr('checked','checked'); //余额默认选上
        cart.select_blance_box();
    }
}

cart.select_blance_box = function() {
    var car_blance_money = $('input[name="car_blance_money"]:checked').val();
    if(car_blance_money === '1') {
        cart.blance_pay_stauts = 1;
        $('.blance-money-box span').addClass('current');
        if(cart.remain_blance_stauts == 1 ) {
            $('#pay-mothed').show();
            $('#remain-money-box').show();
        } else {
            $('#pay_type0').click();
            $('#pay-mothed').hide();
        }
    } else  {
        $('#pay-mothed').show();
        $('#remain-money-box').hide();
        cart.blance_pay_stauts = 0;
        $('.blance-money-box span').removeClass('current');
    }

    var blance_pay_method = 0;
    if(cart.blance_pay_stauts == 1 && cart.remain_blance_stauts == 0) {
        blance_pay_method = 1;
    }

    var pay_type_list = $('#discount_activity').data('pay');
    if(pay_type_list !== '' && pay_type_list !== undefined) {
        //cart.count_show(0,0,"");
    }

    cart.count_show(0,0,"");
}

cart.get_remain_blance_money = function(totalPrice) {
    var totalPrice = parseFloat(totalPrice);
    var blance_money = parseFloat(cart.data.blance_money);
    var remain_blance = 0;

    cart.remain_blance_stauts = 0;
    if(blance_money <  totalPrice) {
        cart.remain_blance_stauts = 1;
        remain_blance = totalPrice - blance_money;
    }
    remain_blance = parseFloat(remain_blance).toFixed(2)
    $('#remain-money').html(base.setNumberDecimals(remain_blance));
    if(common.isZiti()){
        //自提点余额做额外处理
        var payType = $("input[name='pay_type']:checked").val();
        if(payType != 0 && blance_money > 0){
            $('#blance-money-box').show();
            if(cart.remain_blance_stauts == 1) {
                $('#pay-mothed').show();
                if(cart.remain_blance_stauts == 1 ) {
                    $('#remain-money-box').show();
                }
            } else {
                var carBlanceMoney = $('input[name="car_blance_money"]:checked').val()
                if(cart.blance_pay_stauts != 1) {
                    $('#pay-mothed').show();
                    $('#remain-money-box').hide();
                } else {
                    $('#pay-mothed').hide();
                }
            }
        }else{
            if(carBlanceMoney == 1){
                $('#car_blance_money').click();
            }
            $('#pay-mothed').show();
            $('#blance-money-box').hide();
        }
    }else{
        if(blance_money > 0 && !common.isBingoBox()) {
            $('#blance-money-box').show();
            if(cart.remain_blance_stauts == 1) {
                $('#pay-mothed').show();
                if(cart.remain_blance_stauts == 1 ) {
                    $('#remain-money-box').show();
                }
            } else {
                if(cart.blance_pay_stauts != 1) {
                    $('#pay-mothed').show();
                    $('#remain-money-box').hide();
                } else {
                    $('#pay-mothed').hide();
                }
            }
        } else {
            $('#pay-mothed').show();
            $('#blance-money-box').hide();
        }
    }

    if(cart.blance_pay_stauts == 0) {
        $('#remain-money-box').hide();
    }
}

/* 加价购功能扩展，在确定不需要时，可以删除数据 create time 2016/05/12
cart.show_add_price=function(){ //显示加价购
    if (cart.data.add_price==="" ){
        if(actives.user_join_box != 1) {
            actives.user_join_box = 0;
            $('.user-join-actives').hide();
        }
        return false;
    }

    $('#add_price_div').html(cart.data.add_price.event_name);
    var tmp = cart.data.add_price.product;
    actives.user_join_box = 1;
    $('.user-join-actives').show();
    $("#add_price_items").html('');
    for (var i=0;i<tmp.length;i++){
        var str="商品买满"+cart.data.add_price.min_order_fee+"加"+tmp[i].add_price+"元,就可以换取"+tmp[i].title;
        if (tmp[i].add_price == 0){
            str="商品买满"+cart.data.add_price.min_order_fee+",就可以免费获得"+tmp[i].title;
            $('#add_price_div').removeClass('add_price_div');
        } else {
            $('#add_price_div').addClass('add_price_div');
        }

        $("#add_price_div").css('display','block');
        $("#add_price_div").data('info',str);

        var html_tmp=template('./add_price_item', tmp[i]);
        $("#add_price_items").append(html_tmp);

        $('.add-price-model-1').show();
        $('.add-price-name').html('');
        var tmp_fee = Number(cart.order_fruit_sum());
        if(cart.data.add_price_product.id != 0) {
            tmp_fee = Number(cart.order_fruit_sum()) - tmp[i].add_price;
        }
        if (tmp_fee >= Number(cart.data.add_price.min_order_fee)){
            if (tmp[i].add_price==0){ //如果是0元换购，直接选中
                cart.data.add_price_product.id = tmp[i].id;
                cart.data.add_price_product.price = 0;
            }
        } else {
            cart.data.add_price_product.id = 0;
            cart.data.add_price_product.price = 0;
            cart.count_show(0,0,"add_price");
        }
    }
};


cart.select_add_price=function(id,price,kucun) {//选择一个加价购商品
    if(parseInt(kucun) <= 0) {
        tipsBox.createAlertBox('来晚了，没有库存啦');
        return false;
    }
    var fruit_total = cart.order_fruit_sum() - parseFloat(cart.data.add_price_product.price) - parseFloat(cart.special_fruit_total); //加价购，兑换指定水果金额;
    if(fruit_total < Number(cart.data.add_price.min_order_fee)) {
        alertBox('.alert-box','亲，你未达到加价购金额，加把油吧！');
        return false;
    }
    if (cart.data.add_price_product.id==0) {
        cart.data.add_price_product.id = id;
        cart.data.add_price_product.price = price;
        $('#add_price_div').addClass('add-price-join-current');
    }else{
        cart.data.add_price_product.id = 0;
        cart.data.add_price_product.price = 0;
        $('#add_price_div').removeClass('add-price-join-current');
    }
    cart.count_show(0,0,"");
};
*/

cart.show_add_price = function() { //显示加价购
    actives.addPriceOpera(cart.data.add_price);
};

/*
cart.select_add_price2 = function(id,title,price) {

    if(user.userBase.league_id == _activesSwitch) {
        actives.selectSubProduct(id, title, price);
        return false;
    }

    if($('.add-price-selected-'+id).hasClass('current')) {
         $('.add-price-selected-'+id).removeClass('current');
         cart.sub_product_cart[id] = '';
         cart.sub_product_total = parseFloat(cart.sub_product_total) - parseFloat(price);
    } else {
         $('.add-price-selected-'+id).addClass('current');
         cart.sub_product_cart[id] = {"id":id, "title":title, "num":1,"price":price};
         cart.sub_product_total = parseFloat(cart.sub_product_total) + parseFloat(price);
    }

    var sub_product_select = 0;
    for (var k in cart.sub_product_cart) {
        if(cart.sub_product_cart[k] != '') {
            sub_product_select = 1;
        }
    }

    if(sub_product_select == 1) {
        $('#sub_product_tips').addClass('sub_product-current');
    } else {
        $('#sub_product_tips').removeClass('sub_product-current');
    }

    cart.count_show(0,0,"");
} */

/*关闭弹窗*/
cart.hideWindows=function(class_id){
    $("."+class_id).hide();
};
cart.showWindows=function(img){
    $("#addprice_img").attr('src',img);
    $(".addprice-position-wrap").show();
    tipsBoxCenter('.addprice-position-inner');
};
/*显示环保袋*/
cart.showGreenBags=function(){
    $("#green-bags-mask").show();
    $("#green-bags-box").show();
};
/*隐藏环保袋*/
cart.hideGreenBags=function(){
    $("#green-bags-mask").hide();
    $("#green-bags-box").hide();
};
/*参加环保计划*/
cart.greenBagsJoin=function(){
    var url=api_host+"/Api/Users/join_bags_plan";
    var openid=user.userBase.bingo_openid;
    if (openid==undefined || openid==null || openid.length==0){
        return false;
    }
    var data={
        bingo_access_token:openid
        ,bingo_openid:openid
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        if (result.status==1 && result.data==1){
            cart.data.bag.is_join=1;
            cart.data.bags_fee=0;
            cart.count_show(0,0,"");
        }
        if (result.status==1){
            cart.hideGreenBags();
        }else{
            alert("提交失败");
        }
    }});
};
/*开发票*/
function showInvoice(type){
    if (type==1){
        $(".invoice-info-top").show();
    }else{
        $(".invoice-info-top").hide();
    }
}
/*获取收货时间*/
function get_sendTime(type,pay_type) {
    // if(cart.data.cart_type == 2){    //团购
    //     product_id = cart.data.product_list[0].id;
    // }else{
    //     product_id = "";
    // }
    // console.log("tuan",product_id);
    // console.log("tuan",cart.data.product_list[0].id);
    var url = api_host + "/Api/league/get_delivery_time";
    var openid = user.userBase.bingo_openid;
    if (openid == undefined || openid == null || openid.length == 0) {
        return false;
    }
    var data = {
        bingo_access_token: openid
        , bingo_openid: openid
        , is_yugou: (cart.data.cart_type == 2) ? 1 : 0  //"groupbuy|normal"
        , is_show_all: 1
        // ,pid: product_id
    };

    if(cart.data.cart_type == 2) { //团购临时指定,双团购
        data.group_product_id = cart.data.product_list[0].id;
    }

    /*
    if (cart.user_receive_time!=""){
        cart.render_sendTime(type,cart.user_receive_time);
        return false;
    }*/
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        var ret={sendTime:[]};
        var len=result.data.length;
        ret.width=100/len;
        ret.pick=0;  //标识这个是配送时间
        ret.cart_type = cart.data.cart_type;    //标识购物车类型
        for (var i=0;i<len;i++){
            var tmp=result.data[i]["deliver_name"];
            var tmp_arr=tmp.split(" ");
            ret.sendTime.push({day:tmp_arr[0],delivername_name:tmp_arr[1],data:result.data[i]["deliver_time"]});
        }
        if(len != 0){
            cart.timing_voucher = result.data[0].timing_voucher;
            cart.timing_timeout = result.data[0].timing_time;
            cart.timing_cost = result.data[0].cost;
        }

        //渲染
        cart.user_receive_time=ret;
        if(cart.ziti_only == 0) {
            cart.render_sendTime(type,cart.user_receive_time);
        }
    }});
}
/*获取自提时间*/
function get_zitiTime(){
    // if(cart.data.cart_type == 2){    //团购
    //     product_id = cart.data.product_list[0].id;
    // }else{
    //     product_id = "";
    // }
    var url=api_host+"/Api/league/get_delivery_time";
    var openid=user.userBase.bingo_openid;
    if(openid==undefined || openid==null || openid.length==0){
        return false;
    }
    var data={
        bingo_access_token:openid
        ,bingo_openid:openid
        ,is_yugou:(cart.data.cart_type==2)?1:0
        ,is_show_all:1
        ,is_pick:1
        // ,pid: product_id
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        var ret={sendTime:[]};
        var len=result.data.length;
        ret.width=100/len;
        ret.pick=1;   //标识这个是自提时间
        for (var i=0;i<len;i++){
            var tmp=result.data[i]["deliver_name"];
            var tmp_arr=tmp.split(" ");
            ret.sendTime.push({day:tmp_arr[0],delivername_name:tmp_arr[1],data:result.data[i]["deliver_time"]});
        }
        cart.user_ziti_time=ret;
        cart.render_sendTime(0,cart.user_ziti_time);
    }});
}
/*渲染收货时间*/
cart.render_sendTime = function(type,data){
    // console.log(type,data);
     var dom_id="#select-model-01";
        if (type=="#groupbuy"){
            dom_id="select-model-02";
        }
        var html=template('cart_sendTime', data);
        $(dom_id).html(html);
        if(cart.data.cart_type == 2) {
            // $('.select-time-box dd').css('height','80px');
            // $('.select-time-box dd').css('lineHeight','80px');
            $('.group-send-time-tips').show();
        }
}
/*显示收货时间*/
function showDeliveryTime(){
    $('.select-time-mask').show();
    $(".select-time-wrap").show();
}
/*隐藏收货时间*/
cart.hideDeliveryTime = function() {
    $('.select-time-mask').hide();
    $(".select-time-wrap").hide();

    $("html,body").css("overflow","");
    $('#select-model-timing').hide();
}
/*用户选择时间*/
function userSelectTime(_this,str,forwardTime,forwardTime_s){
    var send_type = $('input[name="send_type"]:checked').val();
    if(send_type == 2) {
        str = str.replace('送达', '自提');
    }
    $(".select-time-wrap").hide();
    $(".select-time-mask").hide();
    $("#select-time-title").text(str);
    $("#reciveTime").val(str);
    $("#forwardTime").val(forwardTime);
    $("#forwardTime_s").val(forwardTime_s);
    $('.select-time-box dd').removeClass('current');
    _this.addClass('current');
    var send_type = $('input[name="send_type"]:checked').val();

}

/*
 * 设置用户自提数据,修改隐藏的自提数据,重新赋值
 * @param pareInt type 自提类型,1:送货上门,2:自提
 * @returns void
 */
cart.set_user_ziti = function(type) {
    if( type != 2) {
        return false;
    }
    if(common.isZiti() || common.isBingoBox()){
        var ziti_tel = $('#ziti_tel').val();
        var ziti_name = (user.userBase.nickname != "") ? user.userBase.nickname : "自提用户";
        var addr3 = user.userBase.display_name;
        $("#realname").val(ziti_name);
        $("#tel").val($('#ziti_tel').val());
        $("#addr1").val(select_area.city_list[user.userBase.city_code]);
        $("#addr2").val('用户');
        $("#addr3").val(addr3);
        $("#maplng").val("");
        $("#maplat").val("");
    }else{
        var ziti_tel = $('#ziti_tel').val();
        var ziti_name=user.userBase.nickname!=""?user.userBase.nickname:"自提用户";
        $("#realname").val(ziti_name);
        $("#tel").val(ziti_tel);
        $("#addr1").val(select_area.city_list[user.userBase.city_code]);
        $("#addr2").val('用户');
        $("#addr3").val(cart.ziti_addr);
        $("#maplng").val("");
        $("#maplat").val("");
    }
}

/**
 * 设置订单提交按钮状态
 * @type parseInt status 按钮状态,1:没有提交订单,可用,0:正在提交订单,按钮不可用
 * @returns void
 */
cart.set_submit_btn_status = function(status) {
    switch(status) {
        case 0:
            $('#submiting').show();
            cart.order_allow_submit = 0;
            $("#orderSubmit_btn").html("订单提交中");
            $("#orderSubmit_btn").css('backgroundColor','#CCC');
            $("#orderSubmit_btn").removeAttr('onclick');
            break;
        case 1:
            $('#submiting').hide();
            cart.order_allow_submit = 1;
            $("#orderSubmit_btn").html("提交订单");
            $("#orderSubmit_btn").css('backgroundColor','#6fbfd9');
            $("#orderSubmit_btn").attr('onclick','cart.user_submit_order()');
            break;
    }
}
/**
 * 用户提交订单,防止用户重复提交订单
 * @returns boolen
 */
cart.user_submit_order = function() {
    if(cart.order_allow_submit == 0){
        return false;
    }
    var send_type = $("input[name='send_type']:checked").val();    //送货方式

    if(send_type == 3){   //如果选择了定时达，判断送货时间大于当前时间的55分钟
        var nowDate = common.dateFormat(new Date(),"yyyy-M-d h:m:s");
        var timing_status = cart.timing_comptime(timing_stringtime,nowDate);
        if(timing_status == 0){   //超过5分钟，提示重新选择时间
            tipsBox.createAlertBox('抱歉，您选择的定时达时间不可用，请重新选择～');
            return false;
        }
    }
    var openid = user.userBase.bingo_openid;
    var url = api_host+"/Api/Order/order_submit";
    cart.set_submit_btn_status(0); //防止重复提交

    if(send_type == 2){
        cart.set_user_ziti(send_type);      //设置自提数据
    }

    if(!mid_autumn.submitCheck()) {
        cart.set_submit_btn_status(1);
        return false;
    }

    var params={"realname":"请选择收货地址"
        ,"tel":"请输入联系电话"
        ,"addr1":"请选择收货地址"
        //,"addr2":"请选择收货地址"
        ,"addr3":"请选择收货地址"
        //,"pay_type":"付款方式"
        ,"reciveTime":"请选择收货时间"
        ,"forwardTime_s":"请选择最早收货时间"
        ,"forwardTime":"请选择期待收货时间"
    };

    var sub_data={"bingo_appid":config.appid };
    for (var key in params){
        var tmp=$("input[name="+key+"]").val();
        //if ((tmp==undefined || tmp.length<=0) && key != 'addr2' ){ //修改地址
        if (tmp==undefined || tmp.length<=0){
            tipsBox.createAlertBox(params[key]);
            cart.set_submit_btn_status(1);
            return false;
        }else{
            sub_data[key]=tmp;
        }
    }



    if (cart.data.voucher.code!=0){
        sub_data.voucher_code=cart.data.voucher.code;
    }
    if (cart.data.voucher.selected!=0){
        sub_data.voucher_record_id=cart.data.voucher.selected;
    }
    sub_data.pay_type=$("input[name='pay_type']:checked").val();
    sub_data.is_use_blance = cart.blance_pay_stauts;

    var sub_product_str = '';
    for (var k in cart.sub_product_cart) {
        if(cart.sub_product_cart[k] != '') {
            sub_product_str += '|'+cart.sub_product_cart[k]['id']+','+cart.sub_product_cart[k]['title']+',1,'+cart.sub_product_cart[k]['price'];
        }
    }

    /*
    var buycar = getCookie('buycar');
    buycar = product_weighing.buycartAddWeights(buycar);
    var special_car = getCookie('special_car');
*/
    var cartBase = cart.getCartBaseInfo();
    var buycar = cartBase.buycar;
    var special_car = cartBase.special_car;
    var product_type = cartBase.product_type;
    /*
    if(buycar == null){
        buycar = '';
    }
    if(special_car == null) {
        special_car = '';
    } else {
        if(getCookie('buycar')  != null) {
            special_car = '|'+special_car;
        }
    }*/

    if(special_car !='' && buycar  != '')  {//特价合拼到购物车
        special_car = '|'+special_car;
    }

    sub_data.buycar = buycar + special_car + sub_product_str ;
    sub_data.bingo_access_token=openid;
    sub_data.bingo_openid=openid;
    //sub_data.product_type=cart.get_product_type(); //订单类型
    sub_data.product_type = product_type;
    sub_data.bag_num=cart.data.bags_num;
    sub_data.bag_price=cart.data.bags_fee;
    sub_data.bag_id = cart_bag.id;
    sub_data.olatitude = $("#maplat").val();
    sub_data.olongitude = $("#maplng").val();
    var addressId = $("#address_submitid").val();
    sub_data.address_id = (addressId == 'undefined') ? "" : addressId;    //收货地址ID
    sub_data.app_id = config.appid;
    sub_data.online_discount_pay= cart.data.online_discount_pay;
    sub_data.league_id = user.userBase.league_id;
    if(product_special.headOffice == 1) { //总部发起的特价抢购标识
        sub_data.order_remark = "headOffice";
    }

    if(cart_group.line == 1) { //团购排队
        sub_data.opstatus = -9;
    }

    if(cart.data.cart_type==2){
        sub_data.is_yugou = 1
    }
    sub_data.remark = config.stripscript($("#remark").val());

    sub_data.send_type = send_type;//如果是自提

    if(cart.add_product_cart.selected >= 1) {//加价购id list
        sub_data.add_price_id = actives.createAddProductIdList(cart.add_product_cart);
    }

    /*
    if (cart.data.add_price_product.id != 0){
        sub_data.add_price_id = cart.data.add_price_product.id;
    }*/

    cart.order_allow_submit = 0;
    //如果是套餐水果提交
    if (cart.data.cart_type==3){
        sub_data.package_id=cart.data.package_info.id;
        sub_data.package_pre_id=cart.data.package_info.pre_id;
        //sub_data.product_type=$("#product_type").val();
        sub_data.product_type=$("input[name='product_type']:checked").val();
        sub_data.num=cart.data.all_num;
        //url = "http://test.bingofresh.com/weixinstore-submitOrderPackage.html";
        url=api_host+"/Api/Order/package_order_submit";
        //return false;
    }

    sub_data.activety_id_list = actives.getJoinList();
    if(_minAutumnSwitch == 1) {
        sub_data.order_remark =  JSON.stringify(mid_autumn.order_remark);
    }

    if(common.isZiti() || common.isBingoBox()){
        sub_data.mention = user.userBase.league_type;
    }

    var blance_pay_method = 0;
    if(cart.blance_pay_stauts == 1 && cart.remain_blance_stauts == 0) {
        blance_pay_method = 1;
    }
    $.ajax({type:'post',url:url,data:sub_data,dataType: 'json',success:function(result){
        if (result.status == 1 ){//成功
            cart.noCount = 1;
            common.clear_cookie('buycar');//清除购物车
            product_weighing.productData = [];   //清除称重产品数据
            product_special.clear_submit_after_special_fruit(); //清除特价水果购物车
            //home.synchronous_normal_fruit_kucun(result.data.kucun,user.userBase.league_id);

            cart.init();
            cart_group.line = 0;
            cart_group.order_come_from = 0;
            if(blance_pay_method == 1) { //余额支付跳转
                cart.jump_order_complete_page(result.data.order_id,result.data.orderno,3);
            } else {
                cart.jump_order_complete_page(result.data.order_id,result.data.orderno,sub_data.pay_type);
            }
            return false;
        } else {
            cart.set_submit_btn_status(1);
            tipsBox.createAlertBox('订单提交失败,'+result.data);
        }
    }});
}

/**
 * 测试提交订单，确认不需要时候删除
 * @returns boolen
 */
cart.user_submit_order_test = function() {
    if(cart.order_allow_submit == 0){
        return false;
    }
    var send_type = $("input[name='send_type']:checked").val();    //送货方式

    if(send_type == 3){   //如果选择了定时达，判断送货时间大于当前时间的55分钟
        var nowDate = common.dateFormat(new Date(),"yyyy-M-d h:m:s");
        var timing_status = cart.timing_comptime(timing_stringtime,nowDate);
        if(timing_status == 0){   //超过5分钟，提示重新选择时间
            tipsBox.createAlertBox('抱歉，您选择的定时达时间不可用，请重新选择～');
            return false;
        }
    }
    var openid = user.userBase.bingo_openid;
    var url = api_host+"/Api/Neworder/order_submit";
    cart.set_submit_btn_status(0); //防止重复提交

    if(send_type == 2){
        cart.set_user_ziti(send_type);      //设置自提数据
    }

    if(!mid_autumn.submitCheck()) {
        cart.set_submit_btn_status(1);
        return false;
    }

    var params={"realname":"请选择收货地址"
        ,"tel":"请输入联系电话"
        ,"addr1":"请选择收货地址"
        //,"addr2":"请选择收货地址"
        ,"addr3":"请选择收货地址"
        //,"pay_type":"付款方式"
        ,"reciveTime":"请选择收货时间"
        ,"forwardTime":"请选择期待收货时间"

    };



    var sub_data={"bingo_appid":config.appid };
    for (var key in params){
        var tmp=$("input[name="+key+"]").val();
        //if ((tmp==undefined || tmp.length<=0) && key != 'addr2' ){ //修改地址
        if (tmp==undefined || tmp.length<=0){
            tipsBox.createAlertBox(params[key]);
            cart.set_submit_btn_status(1);
            return false;
        }else{
            sub_data[key]=tmp;
        }
    }


    if (cart.data.voucher.code!=0){
        sub_data.voucher_code=cart.data.voucher.code;
    }
    if (cart.data.voucher.selected!=0){
        sub_data.voucher_record_id=cart.data.voucher.selected;
    }
    sub_data.pay_type=$("input[name='pay_type']:checked").val();
    sub_data.is_use_blance = cart.blance_pay_stauts;

    var sub_product_str = '';
    for (var k in cart.sub_product_cart) {
        if(cart.sub_product_cart[k] != '') {
            sub_product_str += '|'+cart.sub_product_cart[k]['id']+','+cart.sub_product_cart[k]['title']+',1,'+cart.sub_product_cart[k]['price'];
        }
    }

    /*
    var buycar = getCookie('buycar');
    buycar = product_weighing.buycartAddWeights(buycar);
    var special_car = getCookie('special_car');
*/
    var cartBase = cart.getCartBaseInfo();
    var buycar = cartBase.buycar;
    var special_car = cartBase.special_car;
    var product_type = cartBase.product_type;
    /*
    if(buycar == null){
        buycar = '';
    }
    if(special_car == null) {
        special_car = '';
    } else {
        if(getCookie('buycar')  != null) {
            special_car = '|'+special_car;
        }
    }*/

    if(special_car !='' && buycar  != '')  {//特价合拼到购物车
        special_car = '|'+special_car;
    }

    sub_data.buycar = buycar + special_car + sub_product_str ;
    sub_data.bingo_access_token=openid;
    sub_data.bingo_openid=openid;
    //sub_data.product_type=cart.get_product_type(); //订单类型
    sub_data.product_type = product_type;
    sub_data.bag_num=cart.data.bags_num;
    sub_data.bag_price=cart.data.bags_fee;
    sub_data.bag_id = cart_bag.id;
    sub_data.olatitude = $("#maplat").val();
    sub_data.olongitude = $("#maplng").val();
    var addressId = $("#address_submitid").val();
    sub_data.address_id = (addressId == 'undefined') ? "" : addressId;    //收货地址ID
    sub_data.app_id = config.appid;
    sub_data.online_discount_pay= cart.data.online_discount_pay;
    sub_data.league_id = user.userBase.league_id;
    if(product_special.headOffice == 1) { //总部发起的特价抢购标识
        sub_data.order_remark = "headOffice";
    }

    if(cart_group.line == 1) { //团购排队
        sub_data.opstatus = -9;
    }

    if(cart.data.cart_type==2){
        sub_data.is_yugou = 1
    }
    sub_data.remark = config.stripscript($("#remark").val());

    sub_data.send_type = send_type;//如果是自提

    if(cart.add_product_cart.selected >= 1) {//加价购id list
        sub_data.add_price_id = actives.createAddProductIdList(cart.add_product_cart);
    }

    /*
    if (cart.data.add_price_product.id != 0){
        sub_data.add_price_id = cart.data.add_price_product.id;
    }*/

    cart.order_allow_submit = 0;
    //如果是套餐水果提交
    if (cart.data.cart_type==3){
        sub_data.package_id=cart.data.package_info.id;
        sub_data.package_pre_id=cart.data.package_info.pre_id;
        //sub_data.product_type=$("#product_type").val();
        sub_data.product_type=$("input[name='product_type']:checked").val();
        sub_data.num=cart.data.all_num;
        //url = "http://test.bingofresh.com/weixinstore-submitOrderPackage.html";
        url=api_host+"/Api/Order/package_order_submit";
        //return false;
    }

    sub_data.activety_id_list = actives.getJoinList();
    if(_minAutumnSwitch == 1) {
        sub_data.order_remark =  JSON.stringify(mid_autumn.order_remark);
    }

    if(common.isZiti()){
        sub_data.mention = user.userBase.league_type;
    }

    var blance_pay_method = 0;
    if(cart.blance_pay_stauts == 1 && cart.remain_blance_stauts == 0) {
        blance_pay_method = 1;
    }
    $.ajax({type:'post',url:url,data:sub_data,dataType: 'json',success:function(result){
        if (result.status == 1 ){//成功
            cart.noCount = 1;
            common.clear_cookie('buycar');//清除购物车
            product_weighing.productData = [];   //清除称重产品数据
            product_special.clear_submit_after_special_fruit(); //清除特价水果购物车
            //home.synchronous_normal_fruit_kucun(result.data.kucun,user.userBase.league_id);

            cart.init();
            cart_group.line = 0;
            cart_group.order_come_from = 0;
            if(blance_pay_method == 1) { //余额支付跳转
                cart.jump_order_complete_page(result.data.order_id,result.data.orderno,3);
            } else {
                cart.jump_order_complete_page(result.data.order_id,result.data.orderno,sub_data.pay_type);
            }
            return false;
        } else {
            cart.set_submit_btn_status(1);
            tipsBox.createAlertBox('订单提交失败,'+result.data);
        }
    }});
}


/**
 * 获取购物车基本信息
 * @returns {{buycar: *, special_car: *, product_type: string}}
 */
cart.getCartBaseInfo = function(){
    var buycar = getCookie('buycar') || '';
    var special_car = getCookie('special_car') || '';
    var product_type = cart.get_product_type();

    buycar = product_weighing.buycartAddWeights(buycar); //称重水果
    if(product_type != 'groupbuy' && product_type != 'special' && product_type != 'package' ) {
        if(buycar != '' || product_weighing.productData.length > 0) {
            product_type = 'normal';
        }
        if(special_car != '' ) {
            product_type = 'special';
        }
        if(buycar != '' && special_car != '' ) {
            product_type = 'blend';
        }
    }
    var data = { buycar: buycar, special_car: special_car, product_type: product_type };
    return data;
}

/**
 * 订单完成,跳转到相对就页面
 * @param string oid 订单id
 * @param string orderno 订单号
 * @param parseInt type  付款方式,0:货到付款,1:微信支付,2:支付宝支付,3:余额支付
 * @returns void
 */
cart.jump_order_complete_page = function(oid, orderno, type) {
    switch(parseInt(type)) {
        case 1:
            switch (parseInt(_is_app)) {
                case 0:
                    var host = window.location.host;
                    if (host == "test.bingofresh.com"){//测试服务器
                        window.location.href='http://pay.bingofresh.com/wxpay_new/callpayjs.php?is_test=1&showwxpaytitle=1&order_id='+oid;
                    } else if (host == "m.bingofresh.com" || host == "m2.bingofresh.com"){//正式服务器
                        window.location.href='http://pay.bingofresh.com/wxpay_new/callpayjs.php?showwxpaytitle=1&order_id='+oid+'&open_id='+user.userBase.bingo_openid;
                    }
                    break;
                case 1:

                    var host = window.location.host;
                    if (host  == "test.bingofresh.com"){//测试服务器
                        window.location.href='http://pay.bingofresh.com/wxpay_new/App_WxPay.php?is_test=1&order_id=' + oid + '&platform=' + config.appid;
                    } else if (host == "m.bingofresh.com" || host == "m2.bingofresh.com"){//正式服务器
                        window.location.href='http://pay.bingofresh.com/wxpay_new/App_WxPay.php?order_id=' + oid + '&platform=' + config.appid;
                    }
                    //cart.weixin_pay(oid,orderno);
                    break;
            }
            break;
        case 2:
            //window.location.href = 'http://pay.bingofresh.com/alipay/alipayapi.php?showwxpaytitle=1&order_id=' +oid; //生产
            window.location.href = config.pathUrl + 'home.php#/aliPay/'+oid+'/'+orderno;
            break;
        case 3:
            window.location.href = config.pathUrl + 'home.php#/sure_play/'+oid+'/'+orderno;
            break;
        default:
            window.location.href = config.pathUrl + 'home.php#/complete/'+ user.userBase.id +'/'+oid;
    }
}

cart.complete = function(user_id, order_id, order_type) {
     var url= api_host+"/Api/Order/get_order_info";
     var data = {
         user_id:user_id
         ,order_id:order_id
     }
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        var order = {}
        order.orderInfo = result.data.order;
        order.ziti = result.data.ziti;
        order.man_x_give_voucher = result.data.man_x_give_voucher;
        order.user_type = user.userBase.user_type;

        common.renderTpl("#app_content","complete",order);

        $("html,body").scrollTop(0);

        $('#complete-box').css('min-height',$(window).height() - 40 + 'px');
        if(order_type == 'app') {
            $('.complete-footer').hide();
            $('.complete-box').attr('style','');
        }
        $('.back2homeBtn').attr('href','http://'+ window.location.host+"/v3.7");
        $('.viewMyOrderBtn').attr('href','http://'+ window.location.host+"/go.php?go=order");
        common.loaded();
    }});
}

cart.close_voucher=function(){
    $("#cart_voucher").hide();
    $("#buy_cart_div").show();
    $('#app-header').show();
    var top = $('.coupons-info').offset().top;
    $("html,body").scrollTop(top);
    $(".cart-footer").show();
};
/*选择或输入代金券*/
cart.show_voucher=function(){
    $("html,body").scrollTop(0);
    $('#app-header').hide();
    $("#buy_cart_div").hide();
    $('.cart-footer').hide();
    $("#cart_voucher").show();
    //选中
    if (cart.data.voucher!=undefined && cart.data.voucher.selected!=0){
        $(".cart_voucher_item").removeClass("current");
        $("#coupons-item-"+cart.data.voucher.selected).addClass("current");
    }
    /*
    if ($("#cart_voucher").html()!=""){
        return false;
    }
    */
    var url=api_host+"/Api/Voucher/voucher_list";
    var openid=user.userBase.bingo_openid;
    if (openid==undefined || openid==null || openid.length==0){
        return false;
    }
    var buycar = getCookie('buycar');
    buycar = product_weighing.buycartAddWeights(buycar);

    var data={
        bingo_access_token:openid
        ,bingo_openid:openid
        ,type:'unused'
        ,buycar:buycar
        ,is_car:1
    };
    if (cart.data.cart_type==2){
        data.is_group=1;
    }

    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        cart.data.voucher.list=result.data;
        var html=template('cart_voucher', result);
        $("#cart_voucher").html(html);
        $('#cart_voucher').css('height',parseInt($(window).height()) + 'px');
        //选中
        if(cart.data.voucher!=undefined && cart.data.voucher.selected!=0){
            $(".cart_voucher_item").removeClass("current");
            $("#coupons-item-"+cart.data.voucher.selected).addClass("current");
        }
    }});
};
/*选择一张代金券*/
cart.voucher_input_change = function() {
    cart.data.voucher.selected = 0;
    cart.data.voucher.code = 0;
    cart.data.voucher_fee = 0;
    $("#user_voucher_title").text('选择或输入代金券');
    cart.count_show(0,0,"add_voucher");
    $(".cart_voucher_item").removeClass("current");
    return false;
}

cart.voucher_select=function(id){
    //如果选择自己，则取消
    if (cart.data.voucher.selected==id){
        cart.data.voucher.selected=0;
        cart.data.voucher.code=0;
        cart.data.voucher_fee=0;
        $("#user_voucher_title").text('选择或输入代金券');
        cart.count_show(0,0,"add_voucher");
        cart.close_voucher();
        $(".cart_voucher_item").removeClass("current");
        return false;
    }
    var voucher={};
    for (var k in cart.data.voucher.list){
        if (cart.data.voucher.list[k]["id"]==id){
            voucher=cart.data.voucher.list[k];
            break;
        }
    }

    var buycar = getCookie('buycar');
    buycar = product_weighing.buycartAddWeights(buycar);
    if(buycar == null) {
        tipsBox.createAlertBox('特价商品不能使用优惠券');
        return false;
    }

    if(cart.disallow_voucher_status == 1) {
        tipsBox.createAlertBox('您订单中能使用优惠券的商品总价未满足优惠券的使用条件，未能使用此优惠券~');
        return false;
    }

    var voucher_low_money = parseFloat(cart.data.last_total_fee) - parseFloat(cart.special_fruit_total) - parseFloat(cart.disallow_voucher_fee);
    if (parseFloat(voucher.usemin) > voucher_low_money ){
        if(cart.disallow_voucher_fee != 0) {
            tipsBox.createAlertBox('您订单中能使用优惠券的商品总价未满足优惠券的使用条件，未能使用此优惠券~');
        } else {
            tipsBox.createAlertBox('你的购物车中正价商品未达到此优惠券金额');
        }

    } else {
        $("#user_voucher_title").text(voucher.title);
        cart.data.voucher.selected=id;
        cart.data.voucher_fee=voucher.money;
        cart.count_show(0,0,"add_voucher");
        cart.close_voucher();
    }
};
/*切换代金券输入方式*/
cart.showCoupons=function(id) {
    $('.my-coupons-header ul li').removeClass('current');
    if(id == 'cart_voucher_card_div' ) {
        $('.show-money-coupons').addClass('current');
    } else {
        $('.show-gift-coupons').addClass('current');
    }
    $(".showCoupons").hide();
    $("#"+id).show();
};
/*检查礼品券是否可用*/
cart.check_voucher_code=function(){
    var code=$("#voucher_code").val();
    if (code=="" || code.length<=0){
        tipsBox.createAlertBox('请输入礼券密码或邀请码');
        return false;
    }
    var url=api_host+"/Api/Voucher/check_voucher_code";
    var openid=user.userBase.bingo_openid;
    if (openid==undefined || openid==null || openid.length==0){
        return false;
    }
    var buycar = getCookie('buycar');
    buycar = product_weighing.buycartAddWeights(buycar);
    var data={
        bingo_access_token:openid
        ,voucher_code:code
        ,buycar:buycar
        ,bingo_openid:openid
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        if (result.status!=1){
            tipsBox.createAlertBox(result.data);
            return false;
        }
        if (parseFloat(cart.data.last_total_fee)<parseFloat(result.data.money)){
            tipsBox.createAlertBox("亲，您的代金券价值"+result.data.money+"元,但您购买的商品总价才"+cart.data.last_total_fee+"元\n请再选购一些商品吧");
            return false;
        }

        var msg='确定使用吗';
        cart.data.voucher.selected=0;
        cart.data.voucher.code=code;
        $("#user_voucher_title").text(code);
        cart.data.voucher_fee=result.data.money;
        cart.count_show(0,0,"");
        cart.close_voucher();
    }});

};
cart.sendTimeForbidden = function(allow) {
    if(allow == 0) {
         tipsBox.createAlertBox('亲，已经过了送货时间，请选择别的时间段~');
    }
    if(allow == -1) {
         tipsBox.createAlertBox('亲，这个时间段太多人送货了，请选择别的时间段~');
    }
}


cart.weixin_pay = function(id, orderno){
    var url = api_host + "/Api/Pay/weixin_pay";
    var openid = user.userBase.bingo_openid;
    var data = { bingo_access_token: openid, bingo_openid: openid, order_no: orderno };
    $.ajax({type : 'post', url : url ,data : data, dataType : 'json', success:function(result){
        if(result.status == 1) {
            Wechat.sendPaymentRequest(result.data, function () {
                window.location.href = config.pathUrl + '/home.php#/complete/'+user.userBase.id+'/'+id;
            }, function (reason) {
                window.location.href = config.pathUrl + '/home.php#/order/noreceive';
            });
        } else {
            tipsBox.createAlertBox(result.data);
        }
    }});
}


cart.aliPay = function(oid,orderno) {
    var url = api_host + "/Api/Order/get_order_data";
    var openid = user.userBase.bingo_openid;
    var data = { bingo_access_token: openid, bingo_openid: openid, order_id: oid};
    $.ajax({type:'post',url:url,data:data,dataType: 'json', async:false, success:function(result){
        if(result.status == 1){
            result.data.oid = oid;
            result.data.orderno = orderno;
            common.renderTpl("#app_content",'cart/cart_alipay',result.data);
            common.loaded(0);
            $('#back-btn').attr('href','javascript:recharge.returnTips();');
        } else {
            tipsBox.createAlertBox(result.data);
        }
    }});
}

cart.aliPay_pay = function() {
    var oid = $('#aliPay-oid').val();
    var price = $('#aliPay-price').val();
    var tradeNo = $('#aliPay-orderno').val();
    var notifyUrl = 'http://pay.bingofresh.com/alipay/notify_app.php';
    if (window.location.host  == "test.bingofresh.com") {//测试服务器
        notifyUrl = 'http://test.bingofresh.com/pay/alipay/notify_app.php';
    }
    window.alipay.pay({
        tradeNo: tradeNo,
        subject: "缤果精选",
        body: "缤果精选",
        price: price,
        notifyUrl: notifyUrl
    }, function(success) {
        window.location.href = config.pathUrl + 'home.php#/complete/'+ user.userBase.id +'/'+oid;
    }, function(error) {
        if(error.resultStatus == '6001') {
            tipsBox.createAlertBox('你已取消支付');
        } else {
            tipsBox.createAlertBox(error.memo);
        }

    });
}

/*显示自担详细信息*/
function zitiShowInfo() {
    $('.abholung-position-wrap').show();
    tipsBoxCenter('.abholung-position-inner');
}
function zitiHideInfo() {
    $('.abholung-position-wrap').hide();
}

$('.play-box input').live('click',function() {
    $(this).parent().parent().find('label.round').removeClass('current');
    $(this).parent().find('label.round').addClass('current');

    var pay_type_list = $('#discount_activity').data('pay');
    if((pay_type_list !== '' && pay_type_list !== undefined) || user.userBase.league_type == 'hezi') {
        cart.count_show(0,0,"");
    }
});


var cart_bag = {}
cart_bag.init_data = function() {
   cart_bag.id = 0; //购物袋id
   cart_bag.title = ''; //购物袋名字
   cart_bag.price = 0; //购物袋价钱
   cart_bag.bag_data = ""; //购物袋信息
   cart_bag.count = 0;
}
cart_bag.init_data();
cart_bag.init = function() {
    if(cart_bag.id == 0){
        $('.shopping-bag-tips').html('请选择包装');
        $('#mid-autumn-bag h3 span').html('可选择使用包装礼盒(默认使用标准化包装)');
    } else {
        $('.shopping-bag-tips').html('已选"'+cart_bag.title+'"包装');
        $('#mid-autumn-bag h3 span').html('已使用"'+cart_bag.title+'"');
    }
}

/**
 * 创建包装袋数据
 * @param {Objcet} data 包装袋数据
 * @returns {boolean}
 */
cart_bag.create_data = function(data) {
    cart_bag.bag_data = data;
    var html = template('cart_bag', data);
    $('.shopping-bag-wrap').html(html);
}

cart_bag.selectBtn = function(id,title,price) {
    cart_bag.showBoxBtn(0);
    $('#shopping-bag-list li').removeClass('current');
    if(cart_bag.id != id) {
        cart_bag.id = id;
        cart_bag.title = title;
        cart_bag.price = price;
        cart.shopping_bag = '|'+cart_bag.id+','+cart_bag.title+',1,'+cart_bag.price;
        $('.shopping-bag-box-'+id).addClass('current');
        $('.shopping-bag-select-btn span').html('已使用"'+cart_bag.title+'"');
        $('#mid-autumn-bag h3 span').html('已使用"'+cart_bag.title+'"');
    } else {
        cart_bag.id = 0;
        cart_bag.title = '';
        cart_bag.price = 0;
        cart.shopping_bag = '';
        $('.shopping-bag-select-btn span').html('请选择您喜欢的包装');
        $('#mid-autumn-bag h3 span').html('可选择使用包装礼盒(默认使用标准化包装)');
    }
    cart_bag.init();
    cart.count_show(0,0,"");
}
cart_bag.showBoxBtn = function(status) {
    if(status == 1) {
        $('.shopping-bag-wrap').show();

        //按钮点击统计
        common.buttonClikcStatistics("car","car_bag","选择包装袋");
    } else {
        $('.shopping-bag-wrap').hide();
    }
}

cart_bag.get_free_packbag = function(data) { //获得免费包装袋
    if(cart_bag.count == 0) {
        for(var k in data) {
            if(parseInt(data[k]['price']) == 0) {
                cart_bag.id = data[k]['id'];
                cart_bag.title = data[k]['title'];
                cart_bag.price = data[k]['price'];
                cart.shopping_bag = '|'+cart_bag.id+','+cart_bag.title+',1,'+cart_bag.price;
                $('#shopping-bag-box-'+data[k]['id']).addClass('current');
                $('.shopping-bag-select-btn span').html('已使用"'+cart_bag.title+'"');
                $('#mid-autumn-bag h3 span').html('已使用"'+cart_bag.title+'"');
                cart_bag.count++;
                return false;
            }
        }
    }
}
/**
 * Created by wang on 15/1/30.
 */
var cart_group={};
cart_group.line = 0; //团购排队
cart_group.order_come_from = 0;
cart_group.cart=function(id,title,price){
    if(user.is_new_user == 0 && product_group_list[id]['for_new_user'] == 1) {
        tipsBox.createAlertBox(product_group_list[id]['title']+'是新用户专享哦~');
        return false;
    }

    // if(!common.isVip()){
    //     tipsBox.createAlertBox('本次团购是会员专享哦~');
    //     return false;
    // }

    var p=id+","+title+',1,'+price;
    setCookie('buycar',p);
    product_special.execute_clear_operate();
    window.location.href="#/cart/2";

};

cart_group.order_line_up_tips = function(id) { //问用户是否参与排队
    if(confirm("当其他参团用户取消订单后，您的订单将按照排队顺序变为正常订单，确认吗？")) {
          cart_group.user_order_line_up(id,1);
     }
}

cart_group.user_order_line_up = function(id,lineup) { //用户订单排队
    cart_group.order_come_from = 1;
    if(lineup == 1) {
        cart_group.line = lineup;
        cart_group.urlGroup(0,id);
    }
}

/**
 * 微团购跳转
 * @method cart_group.small_group_jume
 * @param {Number} id
 * @param {Number} type 0是普通拼团，1是抽奖拼团
 */
cart_group.small_group_jume = function(id,type) {
    var host = window.location.host;
    if(host == 'test.bingofresh.com') {
        if(type == 0){
            window.location.href = 'http://test.bingofresh.com//actives-black_gallon-index-event_id-'+id+'.html';
        }else{
            window.location.href = 'http://test.bingofresh.com//actives-black_gallon_turntable-index-event_id-'+id+'.html';
        }
    } else {
        if(type == 0){
            window.location.href = 'http://m.bingofresh.com//actives-black_gallon-index-event_id-'+id+'.html';
        }else{
            window.location.href = 'http://m.bingofresh.com//actives-black_gallon_turntable-index-event_id-'+id+'.html';
        }
    }
}

/**
 * 团购是否开启微信支付
 * @method cart_group.groupWeiXinPlay
 */
cart_group.groupWeiXinPlay = function() {
    if(cart.data.cart_type == 2) {
        var buycar = getCookie('buycar');
        if(buycar != null) {
            var all_p = buycar.split("|");
            if (all_p.length > 0 && all_p[0] != "") {
                for (var i = 0; i < all_p.length; i++) {
                    var p = all_p[i].split(',');
                    var id = p[0];
                    var product = product_group_list[id];
                    if (product != undefined && product.tuan_pay == 1) {
                        $('#weixin-pay').show();
                        if(_groupPay.status == 1 &&  _groupPay.gid == product.id ) { //团购临时屏了货到付款
                            $('#location-pay').hide();
                            $('#pay_type1').click();
                        }
                        break;
                    }
                }
            }
        }
    }
}

cart_group.urlGroup = function(cate_id,group_id) {
    var url=api_host+"/Api/Product/product_list";
    var openid=user.userBase.bingo_openid;
    if (openid==undefined || openid==null || openid.length==0){
        return false;
    }
    var data={
        bingo_access_token:openid
        ,bingo_openid:openid
        ,app_id:config.appid
    };
    if (cate_id==1) {  //礼盒套装
        url=api_host+"/Api/Product/product_package_list";
    }
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        var list=result.data;
        user.is_new_user=list.is_new_user; //是否是新用户
        var len=list.product.length;
        for (var i=0;i<len;i++){
            product_list[list.product[i]["id"]]=list.product[i];
        }
        if (cate_id==0) {//团购
            for (var k in list.groupbuy) {
                if (list.groupbuy[k]["tuan_type"] == 2) {
                    var tmp_strt = "";
                    for (var kk = 0; kk < list.groupbuy[k]['rule'].length; kk++) {
                        if (list.groupbuy[k]['rule'][kk]["is_current"] == 1) {
                            list.groupbuy[k]["price"] = list.groupbuy[k]['rule'][kk]["price"];
                        }
                        if (kk > 0) {
                            tmp_strt += "满" + list.groupbuy[k]['rule'][kk]["sum_start"] + "人价格降至" + list.groupbuy[k]['rule'][kk]["price"] + "元;";
                        }
                    }
                    list.groupbuy[k]["show_str"] = tmp_strt;
                }

                list.groupbuy[k]["price"] =  list.groupbuy[k]["tuan_type"] == 1 ?  list.groupbuy[k]["ygprice"] : list.groupbuy[k]["price"];
                list.groupbuy[k]["num"] = 1;
                list.groupbuy[k]['kucun'] = parseInt(list.groupbuy[k]['kucun']);
                list.groupbuy[k]['ygcount'] = parseInt(list.groupbuy[k]['ygcount']);
                list.groupbuy[k]['jian_maxcount'] = parseInt(list.groupbuy[k]['jian_maxcount']);
                product_group_list[list.groupbuy[k]["id"]] = list.groupbuy[k];
            }
            list.product_group_list = product_group_list;

            if(list.product_group_list[group_id]['is_allow_buy'] = 0) {
               window.location.href = '#/home';
                return false;
            } else if(list.product_group_list[group_id]['kucun'] <= list.product_group_list[group_id]['ygcount']) {
                if(cart_group.line == 1) {
                    cart_group.cart(group_id,list.product_group_list[group_id]["title"],list.product_group_list[group_id]["price"]);
                } else {
                    window.location.href = '#/home';
                }
                return false;
            } else if(list.product_group_list[group_id]['status'] == 0) {
                window.location.href = '#/home';
                return false;
            } else {
               cart_group.cart(group_id,list.product_group_list[group_id]["title"],list.product_group_list[group_id]["price"]);
            }
        }else{
            list.product_group_list = {};
        }
    }});
}
var common = {};
common.need_callback = 0;
common.no_juml_url = 0;
common.stop_shop = 0;
common.count_down_name = [];
common.valuation_page = 1;     //评价页数
common.valuation_loadStatus = 1;    //滚动加载状态1可加载，0不可加载

var city_fee = {};
common.user_login = function(callback,param){
    if(user.islogin == 1) {
        if(param == undefined || param == '') {
            tipsBox.dynamicFunction(callback,'');
        } else {
            tipsBox.dynamicFunction(callback,param);
        }
        return false;
    }
    var url = api_host + "/Api/Users/oauth_login";
    var openid = user.userBase.bingo_openid;
    if(openid == undefined || openid == null || openid.length == 0){
        return false;
    }
    if(common.getCookie('openid') == null) {
        common.setCookie('openid',user.userBase.bingo_openid,7);
    }
    var data = {
        bingo_secret : 'fb92390dd7c59c3fcb4fcce4801aadecb79f2e4a'
        ,bingo_appid : config.appid
        ,oauth_type : 4
        ,oauth_openid : openid
    };
    $.ajax({type : 'post', url : url ,data : data, dataType : 'json', success:function(result){
        city_fee = result.data.city_fee;
        if(result.status == "-01009") { //黑名单
            _bingo_blacklist_user = 1;
            if(_bingo_blacklist_user == 1) {
                window.location.href = '#/blacklist';
            }
            return false;
        }
        if (common.need_callback == 1) {
            if(param == undefined || param == '') {
                tipsBox.dynamicFunction(callback,'');
            } else {
                tipsBox.dynamicFunction(callback,param);
            }
            return false;
        }
        if (result.status == 1){
            user.islogin = 1;
            user.userBase = result.data;
            user.userBase.bingo_openid = openid;
            user.userBase.vipBack = null;

            if(common.no_juml_url == 0) {
                if(user.userBase.league_id == '' || user.userBase.league_id == 0 ) {
                    //新用户跳转
                    if(box_model == 1){
                        window.location.href = "#/selectcity";
                        return false;
                    }else{
                        window.location.href="./location.php?league_id=0&city_code=0&open_id="+openid+"&slatitude="+result.data.slatitude+"&slongitude="+result.data.slongitude;
                    }
                }
            }

            if(common.isFendian() && user.userBase.default_address == ""){
                window.location.href = "#/selectcity";
                return false;
            }

            for(var k in user.userBase.city_config) {
                select_area.city_list[user.userBase.city_config[k]['code']] = user.userBase.city_config[k]['name'];
            }

            if(_is_app == 1 && app_cinfig.status == 'close' &&  app_cinfig.come_from == 'outside') {
                app_cinfig.status = 'open';
                window.location.href = '#/notice_list';
                return false;
            }

            if(user.userBase.league_id != '' && user.userBase.league_id != 0 ) {
                if(_come_from != '') { //用户来自外部
                    window.location.href = _come_from;
                    return false;
                }
            }

            if(common.getCookie('come_from') != '' && common.getCookie('come_from') != null ) {
                window.location.href = common.getCookie('come_from');
                return false;
            }

            if(param == undefined || param == '') {
                tipsBox.dynamicFunction(callback,'');
            } else {
                tipsBox.dynamicFunction(callback,param);
            }

        }
    }});
}


common.location_no_tips = function() {
    common.stop_shop_btn();
    common.setCookie('show_location',1,7);
}

common.stop_shop_btn = function() {
    common.stop_shop = 1;
    $('#location-box').html('');
    $('#location-box').hide();
}

common.geolocation = function() { //GPS坐标,bug经常寻问用户坐标
    var show_location = common.getCookie('show_location');
    if(show_location == 1) { //不再提示
        return false;
    }
    var map = new AMap.Map('');
    map.plugin('AMap.Geolocation',function(){
        geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位，默认:true
            timeout: 3000,          //超过5秒后停止定位，默认：无穷大
            maximumAge: 0,           //定位结果缓存0毫秒，默认：0
            convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
            showButton: false,        //显示定位按钮，默认：true
            showMarker: false,        //定位成功后在定位到的位置显示点标记，默认：true
            showCircle: false,        //定位成功后用圆圈表示定位精度范围，默认：true
            panToLocation: false     //定位成功后将定位到的位置作为地图中心点，默认：true
        });

        geolocation.getCurrentPosition();
        AMap.event.addListener(geolocation, 'complete', common.onGeoComplete);//定位成功，返回定位成功信息
        AMap.event.addListener(geolocation, 'error', common.onGeoError);      //定位错误，返回定位出错信息
    });
}

/*定位成功*/
common.onGeoComplete = function(data){
    // console.log("定位成功:",data);
    var position = data.position;
    if(position != "" || position != undefined){
        common.location_tips(position.lng,position.lat);
    }
}

/*定位失败*/
common.onGeoError = function(data){
    // console.log("定位失败");
    return false;
}

common.weixin_geolocation = function(res) {
    var show_location = common.getCookie('show_location');
    if(show_location == 1) { //不再提示
        return false;
    }

    if(_point == null) {
        return false;
    }
    common.location_tips(res.longitude,res.latitude);
}

common.location_tips = function(longitude,latitude) {

    if(_user_select_part == 1) {    //切换分区
        _user_select_part = 0;
        return false;
    }
    if(common.stop_shop == 1) { //停在当前商店
        return false;
    }

    if(longitude == '' ||  latitude == '' ) {
        return false;
    }
    if(browser.versions.iPhone || browser.versions.iPad || browser.versions.ios) {    //IOS用GPS方法解析
        // alert("gprs，" + longitude + "，" + latitude);
        var location_type = "gprs";
    }else{
        // alert("baidu，" + longitude + "，" + latitude);
        var location_type = "baidu";
    }
    var url = api_host + "/Api/league/get_user_auto_league";
    var openid = user.userBase.bingo_openid;
    if(openid == undefined || openid == null || openid.length == 0){
        return false;
    }
    var data = {
        bingo_access_token:openid
        ,bingo_openid:openid
        ,longitude:longitude
        ,latitude:latitude
        ,set_user_league: 0
        ,type: location_type
    };

    $.ajax({type : 'post', url : url ,data : data, dataType : 'json', success:function(result){
        if(result.status != 1  || result.data == "" || result.data.league_id == '') {
            return false;
        }
        result.data.branch_id = result.data.branch_id != '' ? result.data.branch_id : 0;
        user.userBase.branch_id = user.userBase.branch_id != '' ? user.userBase.branch_id : 0;
        if(result.data.league_id == user.userBase.league_id && result.data.branch_id == user.userBase.branch_id ) {
             return false;
        }
        var branch_id = result.data.branch_id != '' ? result.data.branch_id : 0;
        var data = {
            info: '你现在浏览的是'+user.userBase.short_name+'店，与你的现在的位置不一致，是否切换到你的位置（'+result.data.short_name+'）'
            ,old_shop_name: result.data.short_name
            ,now_shop_name: user.userBase.short_name
            ,league_id: result.data.league_id
            ,branch_id: branch_id
        }

        var html = template('location_tips', data);
        $("#location-box").html(html);
        $("#location-box").show();
    }});

}


common.setCookie = function(name,value,days) { //设置cookies函数
    var exp  = new Date();    //new Date("December 31, 9998");
    exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1000);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}
common.getCookie = function (name) { //取cookies函数
    var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
    if(arr != null) return unescape(arr[2]); return null;
}
common.delCookie = function(name) { //删除cookie
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval=getCookie(name);
    if(cval!=null) document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}

common.clear_cookie = function(name) { //清除cookie
    setCookie(name,null,true);
    delCookie(name);
}
common.clear_cookie('show_location');

common.render_account = function() {
    var user_html = template('account', user);
    $("#userBase").html(user_html);
    if(user.userBase.city_code == '') {
         $("#account-user-position a").attr('href','./home.php#/selectcity');
    } else {
        $("#account-user-position a").attr('href','./home.php#/selectcity/'+select_area.city_list[user.userBase.city_code]);
    }
    if(_is_app == 1) {
        $('#li-scan-code').hide();
        $('#li-notice').show();
        $('#login-out').css('display','block');
    }
}



common.loading = function(){ //加载中
    if(_bingo_blacklist_user == 1) {      //黑名单
        window.location.href = '#/blacklist';
    }
    shareOrder.user_share_order = 0;
    var html = template('loading', {});     //加载loading.html模板
    $("html,body").scrollTop(0);
    $("#app_content").html(html);
    $('.transform-left').hide();
    $('#location-box').html('');
    $('#location-box').hide();
    home.show_my_cart_hide();        //清空购物车盒子
    ios_scroll_resert();           //优化IOS滚动
}

common.loaded = function(status) { //加载完成功

    switch(status) {
        case 2:
            ios_scroll();
            load_cookies();
            break;
    }
    //common.user_no_focus();
    notice.returnStatus = 0;
    common.showStart();
    navigation.route();
    common.render_account();
    config.setPageMinHeight();
    config.autoOpenSidebar();
    ios_scroll_resert();
    common.tongji();
    tipsBox.hideTipsBox();
    navigation.returnControl();
    common.appLoaded(0);
}

/**
 * App加载完成事件
 * @type {number} status
 */
common.appLoaded_status = 0;
common.appLoaded = function(status) {
    if(_is_app == 0 || common.appLoaded_status == 1) {
        return false;
    }
    if(status == 0) {
        if(_is_app == 1 && common.appLoaded_status == 0) {
            setTimeout("common.appLoaded(1)",3);
        }
    } else {
        common.appLoaded_status = 1;
        navigator.splashscreen.hide();
    }
}

setTimeout("common.closeStart()",8000);

common.showStart = function() {
    if($('#start-start').val() == 1) {
        setTimeout("common.closeStart()",8000);
    } else {
        $('#start').hide();
    }
}

common.closeStart = function() {
    $('#start').hide();
}

common.blacklist = function() { //黑名单
    var html = template('loading', {});
    $("html,body").scrollTop(0);
    $("#app_content").html(html);
    $('.transform-left').hide();
    ios_scroll_resert();
    $('.loading-wrap p').html('进入缤果商城错误哦!!!');
}

common.user_no_focus = function() {  //用户没有关注
    if(user.userBase.user_type != 1) {
        $('#user-no-focus').show();
        if (browser.versions.iPhone || browser.versions.iPad || browser.versions.ios) {
            $('#user-no-focus-height').css('height',$('#user-no-focus').height()+'px');
        } else {
            $('#view_page').css('paddingTop',$('#user-no-focus').height()+'px');
        }
    }
}

common.get_array_key = function(arr, value) { //获得数组的key值
    for(var key in arr){
        if(arr[key]  == value) {
            return key;
        }
    }
    return false;
}

/**
 * 对日期进行格式化，
 * @param date 要格式化的日期
 * @param format 进行格式化的模式字符串
 *     支持的模式字母有：
 *     y:年,
 *     M:年中的月份(1-12),
 *     d:月份中的天(1-31),
 *     h:小时(0-23),
 *     m:分(0-59),
 *     s:秒(0-59),
 *     S:毫秒(0-999),
 *     q:季度(1-4)
 * @return String
 */
common.dateFormat = function(date,format) {
    date = new Date(date);
    var map = {
        "M": date.getMonth() + 1, //月份
        "d": date.getDate(), //日
        "h": date.getHours(), //小时
        "m": date.getMinutes(), //分
        "s": date.getSeconds(), //秒
        "q": Math.floor((date.getMonth() + 3) / 3), //季度
        "S": date.getMilliseconds() //毫秒
    };
    format = format.replace(/([yMdhmsqS])+/g, function(all, t){
        var v = map[t];
        if(v !== undefined){
            if(all.length > 1){
                v = '0' + v;
                v = v.substr(v.length - 2);
            }
            if(t === 'h' || t === 'm' || t === 's') {//时分秒
                if(parseInt(map[t]) < 10 ) {
                    v = '0' + parseInt(map[t]);
                }
            }
            return v;
        } else if(t === 'y'){
            return (date.getFullYear() + '').substr(4 - all.length);
        }
        return all;
    });
    return format;
}


/**
 * 数字格式化,例如:8888 变成 8.888
 */
common.numFormat = function(nStr) {
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}
common.removeCity = function(city) {
    return city.replace('市','');
}

common.remainTime = function(start, end) {
    var Times = end - start ;
    var html = '';
    if (Times >= 0){
        var D = parseInt(Times / 86400);
        var H = parseInt((Times - D * 86400)/3600);
        var i = parseInt((Times -D * 86400 - H * 3600) / 60);
        var s = Times - H * 3600-i * 60-D * 86400;
        if (D != 0) {
            html = "<strong>"+D+"天</strong><strong><em>"+H+"</em><i>小时</i></strong><strong><em>"+i+"</em><i>分</i></strong>";
        } else {
            if(H != 0){
                html = "<strong><em>"+H+"</em><i>小时</i></strong><strong><em>"+i+"</em><i>分</i></strong>";
            } else {
                if(i != 0){
                    html = '<strong><em>'+i+'</em><i>分<i></strong>';
                }else{
                    html = '0分钟';
                }
            }
        }
    } else {
        html = '0分钟';
    }
    return html;
}

common.sendTimeFormat = function(data,type) {
    switch(type) {
        case 0:
           if(data.indexOf("-") != -1) {
                var index = data.indexOf("-") + 1;
                data = data.substring(index);
            }
            break;
       case 1:
           data = data.replace("送达","");
           break;
    }
    return data;
}

common.tongji = function() { //统计购物车中产品数量与金额
    if(config.cartType != 0) {
        return false;
    }
    var normal_fruit =  common.subtotal_car('buycar'); //正常水果购物车
    var special_fruit =  common.subtotal_car('special_car'); //特价水果购物车
    var num = parseInt(normal_fruit.num) + parseInt(special_fruit.num) + parseInt(product_weighing.productData.length);

    //计算称重产品的总价
    var product_weighing_price = 0;
    $.each(product_weighing.productData, function(j){
        product_weighing_price += parseFloat(product_weighing.productData[j].price);
    });

    // var price = parseFloat(normal_fruit.price) + parseFloat(special_fruit.price) + parseFloat(product_weighing_price);
    var price = base.setNumberDecimals(normal_fruit.price) + base.setNumberDecimals(special_fruit.price) + base.setNumberDecimals(product_weighing_price);
    price = base.setNumberDecimals(price);
    var gap_fee = parseFloat(city_fee.fee_free) - price;    //运费标准与金额差距
    // var gap_fee = base.setNumberDecimals(parseFloat(city_fee.fee_free) - price);    //运费标准与金额差距
    if (num > 0){
        $('#footer-product-btn').attr("href","#/cart/0");
        $("#cart-btn").attr("href","#/cart/0");
        $("#cart_num").show().text(num);

        if(config.elementIsExist('common-footer')) {
            $("#cart_price").html("去结算 ￥" + price);
            $("#cart_price").removeClass('cart_price');
        } else {
            if(user.is_new_user == 1 || common.isZiti() || common.isBingoBox()){
                //新用户首单或者是自提点或者是盒子
                $("#cart_price").html("去结算 ￥" + price);
                $("#cart_price").removeClass('cart_price');
            }else{       //老用户
                if(gap_fee > 0){
                    if(gap_fee > parseInt(gap_fee)){
                        gap_fee = gap_fee.toFixed(1);
                    }
                    $("#cart_price").html("去结算 ￥" + price + "<br\><span class='gap_fee'>还差" + gap_fee + "元免运费</span>");
                    $("#cart_price").addClass('cart_price');
                }else{
                    $("#cart_price").html("去结算 ￥" + price);
                    $("#cart_price").removeClass('cart_price');
                }
            }
            $('#footer-product-btn').html('结算: &yen; ' + price);
        }

    } else {

        var url = '#/home';
        if(home.first_product_class != '') {
            url = '#/home/' + home.first_product_class;
        }
        var page = $('#page-mark').val();
        if(page == 'street') {
            url = '#street';
        }
        $('#footer-product-btn').attr("href",url);
        $('#footer-product-btn').html('去选购商品');
        if(config.elementIsExist('common-footer')) {
            $("#cart_price").removeClass('cart_price');
            $("#cart-btn").attr("href",url);
            $("#cart_price").html("请选择商品");
        } else {
            $("#cart_price").removeClass('cart_price');
            $("#cart-btn").attr("href", url);
            $("#cart_price").html("<i>&yen</i>0");
        }
        $("#cart_num").hide().text('0');
    }
    navigation.setShoppingCartSize();
}

common.isOwnEmpty = function(obj) { //对象是否为空
    for(var name in obj) {
        if(obj.hasOwnProperty(name)){
            return false;
        }
    }
    return true;
};

/**
 * 参数为空
 * @param {String} value 参数
 * @returns {boolean}
 */
common.isNull = function(value) {
    if(typeof(value) == "undefined" || typeof(value) == "null" || value ==undefined ||  value == null || value == "") {
        return true;
    } else {
        return false;
    }
}

/*common.tongji = function() { //统计购物车中产品数量与金额
    var normal_fruit =  common.subtotal_car('buycar'); //正常水果购物车
    var special_fruit =  common.subtotal_car('special_car'); //特价水果购物车
    var num = parseInt(normal_fruit.num) + parseInt(special_fruit.num);
    var price = parseFloat(normal_fruit.price) + parseFloat(special_fruit.price);
    if (num > 0){
        $("#cart-btn").attr("href","#/cart/0");
        $("#cart_num").text(num);
        $("#cart_price").text("去结算 ￥"+price);
    }else{
        $("#cart-btn").attr("href","#/home");
        $("#cart_num").text('0');
        $("#cart_price").text("请选择水果");
    }
}*/



common.subtotal_car = function(car_name) { //计算购物车数量与总价
    var num = 0;
    var price = 0;
    var buycar = getCookie(car_name);
    if(buycar != null) {
        var all_p = buycar.split("|");
        if(all_p.length > 0 && all_p[0] != "") {
            for (var i = 0; i < all_p.length; i++) {
                var p = all_p[i].split(',');
                if (p.length<4){
                    break;
                }
                price += p[2] * p[3] || 0;
                num += Number(p[2]) || 0;
            }
            if(price > parseInt(price)) {
                price = price.toFixed(2);
            }
        }
    }
    return {num:num,price:price};
}

common.clear_car = function() { //清除购物车cookie值
    setCookie('buycar', null, true);
    delCookie('buycar');
    setCookie('special_car', null, true);
    delCookie('special_car');
    setCookie('street_cart', null, true);
    delCookie('street_cart');
    common.delCookie('buycar');
    common.delCookie('special_car');
    common.delCookie('street_cart');
}

common.count_down = function(id, remainTime, serverTime){
    var start = serverTime;
    var end = parseInt(serverTime) + parseInt(remainTime);
    if (isNaN(end) || isNaN(start)){
        return false;
    }
    clearTimeout(common.count_down_name[id]);
    common.count_down_show(id,remainTime);
};

common.count_down_show = function(id,remainTime){
    if (remainTime >= 0){
        var D = parseInt(remainTime / 86400);
        var H = parseInt((remainTime - D * 86400)/3600);
        var i = parseInt((remainTime -D * 86400 - H * 3600) / 60);
        var s = remainTime - H * 3600-i * 60-D * 86400;
        var html = '';
        if (D != 0) {
            html = "<em>"+D+"</em>天<em>"+H+"</em>小时<em>"+i+"</em>分<em>"+s+"</em>秒";
        } else {
            if(H != 0){
                html = "<em>"+H+"</em>小时<em>"+i+"</em>分<em>"+s+"</em>秒";
            } else {
                if(i != 0){
                    html = "<em>"+i+"</em>分<em>"+s+"</em>秒";
                } else {
                    html = "<em>"+s+"</em>秒";
                }
            }
        }
        remainTime--;
        $('#'+id).html(html);
        clearTimeout(common.count_down_name[id]);
        common.count_down_name[id] = setTimeout("common.count_down_show('"+id+"','"+remainTime+"')",1000);
    } else {
        $('#'+id+'-box').remove();
        clearTimeout(common.count_down_name[id]);
        recharge.recharge_ice_jumb();
    }
}

common.share_url_record = function(active_type, active_content) {
    var url = api_host+"/Api/Weixin/active_record";
    var openid = user.userBase.bingo_openid;
    var data = { bingo_access_token: openid,bingo_openid: openid, active_type: active_type, active_content:active_content};
    $.ajax({type: 'post', url: url, data: data, dataType: 'json', async: false, success: function(result){
        // console.log(result);
    }});
}

/**
 * 没有找到数据
 * @method common.noFoundResult
 * @param {String} tips 提示
 */
common.noFoundResult = function(tips, id) {
    var id = (id != undefined) ? id : '#common-no-result';
    var data = { 'tips': tips };
    var html = template('common/common_no_result', data);
    $(id).html(html);
}

/**
 * 渲染模板
 * @method ncommon.renderTpl
 * @param {Stinrg} id id名称
 * @param {String} tpl 模板名称
 * @param {Object} data 数据
 */
common.renderTpl = function(id, tpl, data) {
    var html = template(tpl, data);
    $(id).html(html);
}

/**
 * 查看或关闭商品评价
 * @method common.checkProductValuation
 * @param {String} id 产品id
 * @param {String} status 状态：0为关闭评价窗口
 */
common.checkProductValuation = function(id,status){
    if(status == 0){      //关闭评价
        $("#product-valuation").hide().html("");
        base.recoverPenetration();      //恢复底层滚动
        common.valuation_page = 1;    //重置评价页数
        common.valuation_loadStatus = 1;   //防止重复加载
        $('.product-valuation-scroll').unbind('scroll');    //解除滚动绑定
        return false;
    }
    if(!base.checkBtnLock()){    //防止重复提交
        return false;
    }
    //加载loading
    $('.valuation-loading-mark').show();
    $('.valuation-loading-box').show();
    common.getProductValuation(0,id);
}

/**
 * 获取商品评论
 * @method common.getProductValuation
 * @param {Number} trantype 类型
 * @param {Number} id 产品id
 */
common.getProductValuation = function(trantype,id){
    if(common.valuation_loadStatus == 0){
        return false;
    }
    if(id == -1){
        id = $('#valuation_product_id').val();
        $('#valuation-loaded').text('正在加载中....');
    }

    common.valuation_loadStatus = 0;    //防止重复加载

    var pages = 30;   //每页评论数
    var url = api_host+"/Api/AfterSale/get_pingjia_list";
    var openid = user.userBase.bingo_openid;
    if (openid == undefined || openid == null || openid.length == 0){
        return false;
    }
    var data = {
        bingo_access_token: openid,
        bingo_openid: openid,
        pid: id,
        page_next: common.valuation_page,
        pages: pages
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        base.clearBtnLock();     //解锁按钮
        if(trantype == 0){    //获取第一页评论
            if(result.status != 1) {
                //关闭loading
                $('.valuation-loading-mark').hide();
                $('.valuation-loading-box').hide();
                tipsBox.createAlertBox(result.data);
                common.valuation_loadStatus = 1;    //防止重复加载
                return false;
            }
            if(result.data == ""){
                //关闭loading
                $('.valuation-loading-mark').hide();
                $('.valuation-loading-box').hide();
                tipsBox.createAlertBox("该商品暂时没有任何评价哦～");
                common.valuation_loadStatus = 1;    //防止重复加载
                return false;
            }
            result.product_share_status = product_share_status;     //判断是分享的详情页还是商场里面的
            common.valuation_page++;
            // console.log(common.valuation_page);
            common.renderTpl("#product-valuation",'product_valuation',result);
            $("#product-valuation").show();
            //关闭loading
            $('.valuation-loading-mark').hide();
            $('.valuation-loading-box').hide();
            $('#valuation_product_id').val(id);

            base.preventPenetration();    //防止滚动穿透
            common.valuation_loadStatus = 1;    //防止重复加载
            if(result.data.length < pages){
                $('#valuation-notmore').removeClass('hide');
                $('#valuation-loaded').addClass('hide');
                return false;
            }
            common.checkValuationScroll();     //监听滚动
        }else{     //通过监听滚动获取的评论
            if(result.status != 1 || result.data == "") {
                //没有更多评论了
                $('#valuation-notmore').removeClass('hide');
                $('#valuation-loaded').addClass('hide');
                return false;
            }
            common.valuation_page++;
            var data = result.data;
            var html = "";

            for(var i = 0,len = data.length; i < len; i++){
                var lidoom = "";
                var paris = "";
                if(data[i].avatar == null || data[i].avatar == ""){
                    data[i].avatar = 'ui/images/standard_avatar.jpg?v=1';
                }
                if(data[i].nickname == null || data[i].nickname == ""){
                    if(data[i].uid == null){
                        data[i].uid = "";
                    }
                    data[i].nickname = '用户'+ data[i].uid;
                }
                if(product_share_status == 0){    //分享出去的页面没有点赞功能
                    if(data[i].is_prais == 1){
                        paris = '<div class="valuation-prais" id="valuation-prais-' + data[i].id + '" data-lock="unlock"><a href="javascript:common.fruitLikeBtn(' + data[i].id + ',\'#valuation-prais-' + data[i].id + '\');" class="current"><i class="icon-heart"></i><span>' + data[i].comment_likes + '</span></a></div>'
                    }else{
                        if(data[i].comment_likes == 0){
                            data[i].comment_likes = '赞';
                        }
                        paris = '<div class="valuation-prais" id="valuation-prais-' + data[i].id + '" data-lock="unlock"><a href="javascript:common.fruitLikeBtn(' + data[i].id + ',\'#valuation-prais-' + data[i].id + '\');" ><i class="icon-heart-empty"></i><span>' + data[i].comment_likes + '</span></a></div>'
                    }
                }
                for(var j = 0,len2 = data[i].mark_comment.length; j < len2; j++){
                    lidoom += '<li class="textComColor">' +  data[i].mark_comment[j].txt + '</li>';
                }
                html += '<div class="product-valuation-item">';
                html +=     '<div class="top-user-info">';
                html +=         '<div class="user-info-img">';
                html +=             '<div>';
                html +=                 '<img src="' + data[i].avatar + '" alt="头像">';
                html +=             '</div>';
                html +=         '</div>';
                html +=         '<div class="user-info">';
                html +=             '<p class="textComColor">' + data[i].nickname + '</p>';
                html +=             '<p>' + data[i].create_time +'</p>';
                html +=         '</div>';
                html +=         paris;
                html +=     '</div>';
                html +=     '<div class="valuation-info">' + data[i].comment + '</div>';
                html +=     '<div class="valuation-tag">';
                html +=         '<ul>' + lidoom + '</ul>';
                html +=     '</div>';
                html += '</div>';
            }
            $("#valuation-wrap").append(html);
            $('#valuation-loaded').text('下拉加载更多');

            if(result.data.length < pages){
                $('#valuation-notmore').removeClass('hide');
                $('#valuation-loaded').addClass('hide');
            }
            common.valuation_loadStatus = 1;    //防止重复加载
        }

    }});

    //按钮点击统计
    var page = $('#page-mark').val();
    if(page == 'product-info'){
        //产品详情页
        common.buttonClikcStatistics("view","view_valuation","查看评价");
    }else if(page == 'appraise'){
        //订单评价页
        common.buttonClikcStatistics("appraise","appraise_checkValuation","查看评价");
    }
}

/**
 * 产品评论点赞按钮
 * @method common.fruitLikeBtn
 * @param {Number} vid 评论id
 * @param {String} dom 评论item
 */
common.fruitLikeBtn = function(vid,dom){
    if($(dom).data('lock') == 'lock'){
        //防止重复提交
        return false;
    }
    if($(dom).find('a').hasClass('current')){
        //已经点过赞
        return false;
    }
    $(dom).data('lock','lock');    //锁死当前按钮
    var praisNum = parseInt($(dom).find('span').text());
    if(praisNum > 0){   //已有点赞
        if(praisNum >= 999){     //当点赞数大于999时默认都显示为999
            praisNum = 999;
        }else{
            praisNum = praisNum + 1;
        }
    }else{    //一个点赞都没有
        praisNum = 1;
    }

    var url = api_host+"/Api/AfterSale/comment_prais";
    var openid = user.userBase.bingo_openid;
    if (openid == undefined || openid == null || openid.length == 0){
        return false;
    }
    var data = {
        bingo_access_token: openid,
        bingo_openid: openid,
        appraise_id: vid
    };
    $.ajax({type: 'post',url: url,data: data,dataType: 'json',success:function(result){
        if(result.status == 1){
            $(dom).find('a').addClass('current');
            $(dom).find('i').toggleClass('icon-heart-empty');
            $(dom).find('i').toggleClass('icon-heart');
            // $(dom).find('i').addClass('header-bigger-small');    //会导致iphone的微信客户端闪退
            $(dom).find('span').text(praisNum);
            $(dom).data('lock','unlock');      //解锁当前按钮
        }
    }});
}

/**
 * 绑定监听评价列表滚动条
 * @method common.checkValuationScroll
 */
common.checkValuationScroll = function(){
    var nScrollHight = 0; //滚动距离总长
    var nScrollTop = 0;   //滚动到的当前位置
    var nDivHight = $(".product-valuation-scroll").height();
    $('.product-valuation-scroll').on("scroll",function(){
        if(!$('#valuation-notmore').hasClass('hide')){
            //已经全部加载完
            return false;
        }
        nScrollHight = $(this)[0].scrollHeight;
        nScrollTop = $(this)[0].scrollTop;
        if (nScrollTop + nDivHight >= nScrollHight){     //滚动到底了
            common.getProductValuation(1,-1);
        }
    });
}

/**
 * 按钮点击次数统计
 * @method common.buttonClikcStatistics
 * @param {String} pageId 页面ID
 * @param {String} btnId 按钮ID
 * @param {String} btnName 按钮名称
 */
common.buttonClikcStatistics = function(pageId,btnId,btnName){
    var pageName = "";     //页面名称
    switch(pageId){
        case "index":
            pageName = "商城首页";
            break;
        case "car":
            pageName = "结算页";
            break;
        case "account":
            pageName = "个人菜单页";
            break;
        case "noreceive":
            pageName = "未收货订单页";
            break;
        case "receive":
            pageName = "已收货订单页";
            break;
        case "view":
            pageName = "产品详情页";
            break;
        case "scan":
            pageName = "商品扫一扫页";
            break;
        case "appraise":
            pageName = "订单评价页";
            break;
        case "exchange":
            pageName = "退换货页面";
            break;
        default:
            pageName = "未知页面";
    };

    var isAppleDevice = config.isAppleDevice == 1 ? 1 : 2;
    var appid = config.appid == 1 ? 1 : 2;

    var url = api_host + "/Api/BaseService/bingo_store_op_data";
    var data={
        parent_page: pageId
        ,parent_page_name: pageName
        ,sub_button: btnId
        ,sub_button_name: btnName
        ,platform: isAppleDevice    //操作设备，1苹果、2安卓
        ,store_type: appid  //商城类型，1微信、2APP
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        if(result.status == 1){
            return false;
        }
    }});
}

/**
 * 判断用户是否是缤果会员
 * @method common.isVip
 * @return {Boolean}
 */
common.isVip = function(){
    if(user.userBase.level_id != 0 && user.userBase.memeber_time_out != 1 && (user.userBase.city_code == "0760" || user.userBase.city_code == "0756")){
        return true;
    }else{
        return false;
    }
}

/**
 * 判断当前分店是否是缤果自提点或缤果盒子功能灰度测试点
 * @method common.isZitiTest
 * @return {Boolean}
 */
common.isZitiTest = function(){
    if(box_model == 1 && (user.userBase.league_id == '10' || user.userBase.league_id == '13' || user.userBase.league_type == 'hezi' || user.userBase.league_type == 'BingoBox') && user.userBase.branch_id == ""){
        return true;
    }else{
        return false;
    }
}

/**
 * 判断当前分店是否是缤果自提点
 * @method common.isZiti
 * @return {Boolean}
 */
common.isZiti = function(){
     if(box_model == 1 && user.userBase.league_type == 'hezi' && user.userBase.branch_id == ""){
         return true;
     }else{
         return false;
     }
 }

 /**
  * 判断当前是缤果自提点或缤果盒子功能灰度测试点并且是分店
  * @method common.isFendian
  * @return {Boolean}
  */
common.isFendian = function(){
    if(box_model == 1 && (user.userBase.league_id == '10' || user.userBase.league_id == '13') && user.userBase.league_type == 'fendian' && user.userBase.branch_id == ""){
        return true;
    }else{
        return false;
    }
 }

/**
 * 判断当前是否是缤果盒子
 * @method common.isBingoBox
 * @return {Boolean}
 */
common.isBingoBox = function(){
    if(box_model == 1 && user.userBase.league_type == 'BingoBox' && user.userBase.branch_id == ""){
        return true;
    }else{
        return false;
    }
}

/**
 * 显示/关闭 滚动提示框
 * @method common.tipsBoxScroll
 * @param {String} HTML
 */
common.tipsBoxScroll = function (html) {
    if(html != undefined){
        $('#tipsBoxScroll-content').html(html);
        base.preventPenetration();
    }else{
        base.recoverPenetration();
    }
    $('#tipsBoxScroll').toggle();
}

/**
 * 显示/隐藏透明居中的loading
 * @method common.transparentLoading
 */
common.transparentLoading = function(){
    $('.valuation-loading-mark').toggle();
    $('.valuation-loading-box').toggle();
}

/**
 * 监听浏览器历史记录,解决使用base.preventPenetration后android端使用返回键导致页面锁死无法滚动的情况
 */
window.onpopstate = function(event) {
    if($('#app_content').hasClass('cancel-scroll')){
        common.valuation_page = 1;    //重置评价页数
        common.valuation_loadStatus = 1;   //防止重复加载
        $('.product-valuation-scroll').unbind('scroll');    //解除滚动绑定
        base.recoverPenetration();
    }
}
/**
 * web的配置环境
 * 定义通用变量、函数,减少代码量, 提高代码质量
 */
var config = {};
config.version = 'v3.7';
config.host = "http://" + window.location.host;
config.pathUrl = config.host + "/" + config.version + "/";
config.width = $(window).width();
config.height = $(window).height();
config.scrollTop = 0;
config.scrollTopRecord = 0; //存储用户滚动的高度
config.isAppleDevice = 0; //是否苹果设备
config.cartType = 0; //购物车类型
config.openSidebar = 0; //打开菜单
config.appShareUrl = config.host + '/v3.7/web_share/index.php';
config.appid = 1; //用户环境,1:微信,2:ios, 3:安桌
config.appIsHasVersion = 0;

/**
 * 配置环境初始化
 * @method config.init
 */
config.init = function() {
    common.clear_car(); //删除购物车产品
    //cart_bag.init_data(); //包装袋初始货
    config.getUserAgent(); //识别用户的设备:ios与安桌
    //weixin_share.share_init(); //微信方案初始化
    config.getDevice();//获得当前设备环境
}

/**
 * 获得当前设备
 * @method config.device
 */
config.getDevice = function() {
    if(_is_app == 1) {
        if(config.isAppleDevice == 1) {
            config.appid = 2;
        } else {
            config.appid = 3;
        }
    }
}

/**
 * 购物车初始化
 * @method config.cart_init
 */
config.cart_init = function() {
    if(config.cartType != 0) {
        GL_SELECTED = {};
        for(var i in product_list) {
            product_list[i].num = 0;
        }
        common.clear_cookie('buycar');
        config.cartType = 0;
    }
}

/**
 * 获得购物车原始数据
 * @method street_cart.getCartInitDat
 * @param {String} name 购物车名字
 */
config.getCartInitData = function(name) {
    var cart = common.getCookie(name);
    if (cart !== null && cart != ''){
        return cart.split('|');
    }
    return new Array();
}

/**
 * 加入购物车
 * @method street_cart.AddCart
 * @param {String} name 购物车名字
 * @param {Number} id 商品id
 * @param {String} title 商品名称
 * @param {Number} num 商品数量
 * @param {Number} price 商品价钱
 */
config.AddCart = function(name, id, title, num, price){
    var has = false, item = null;
    var cart = config.getCartInitData(name);
    for(var i in cart) {
        item = cart[i].split(',');
        if(item[0] == id) {
            item[2] = num;
            item[3] = price;
            if(num <= 0) {
                cart.splice(i,1);
            } else {
                cart[i] = item.join(',');
            }
            has = true;
            break;
        }
    }

    if(!has && num > 0) {
        cart.push(id + ',' + title + ',' + num + ',' + price);
    }

    cart = cart.join('|');
    common.setCookie(name, cart, 30);
}


/**
 * 开启web右侧菜单栏
 * @method config.openRightSidebar
 * @param {String} clickType 按钮点击统计类型
 * @param {Srting} btnName 按钮名称
 */
config.openRightSidebar = function(clickType,btnName) {
    var rightWidth = $(window).width();
    if(!$('.transform-wrap').hasClass('isTransform')) {
        var height = $(window).height();
        $('.transform-wrap').css('-webkit-transform', 'translateX(-'+rightWidth+'px)');
        $('.transform-wrap').css('transform', 'translateX(-'+rightWidth+'px)');
        $('.fixed-wrap').css('right',rightWidth+"px");
        $('.snap-drawers').css('height',height);
        $('.snap-drawers').css('width',rightWidth+'px');
        $('.fixed-wrap').css('left','inherit');
        $('.transform-wrap').addClass('isTransform');
        $('.snap-drawers').show();
        $('#rightSidebar').show();
        $('.user-account-footer').show();
        $('.close-sidebar').show();

        $('#view_page').hide();
        $('#retun-top-btn').hide();
        notice.control('sidebar');
        config.scrollTopRecord = config.scrollTop;

        //如果用户是VIP
        if(common.isVip()){
            if(user.userBase.vipBack == null){
                //接口获取会员返现进度
                vip.getVipCashBack();
            }else{
                var data = user.userBase.vipBack;
                var html = "";
                if(data.shengyu == 0){
                    $('#ac-cashBackProgressDiv').addClass('progress100').css('width','100%');
                    html = '您已获取本月全部返现额度!';
                }else{
                    $('#ac-cashBackProgressDiv').css('width', data.benci + '%');
                    var benci = base.setNumberDecimals(data.benci);
                    var bencishenyu = base.setNumberDecimals(100 - benci);
                    html = '当前返现消费进度为' + data.benci + '元<br>还差<span style="color: #fff606;">' + bencishenyu + '</span>元即可获取5元余额返现';
                }
                $('#vip-cash-back p').html(html);
            }
        }


        var page = $('#page-mark').val();
        if(page == "home"){
            //按钮点击统计
            common.buttonClikcStatistics("index","index_active","个人菜单");
        }

    } else {
        config.openSidebar = 1;
        $('#view_page').show();
        $("html,body").scrollTop(config.scrollTopRecord);
        $('.transform-wrap').css('-webkit-transform', 'none');
        $('.transform-wrap').css('transform', 'none');
        $('.fixed-wrap').css('right',0+"px");
        $('.fixed-wrap').css('left','0');
        $('.transform-wrap').removeClass('isTransform');
        $('.snap-drawers').hide();
        $('#rightSidebar').hide();
        $('.user-account-footer').hide();
        $('.close-sidebar').hide();
        if (config.scrollTopRecord > config.height) {
            $('#retun-top-btn').show();
        }
        config.lazyLoadImage();

        if(clickType != undefined && btnName != undefined){
            common.buttonClikcStatistics("account",clickType,btnName);
        }
    }
}

/**
 * 自动开启右侧菜单
 * @method config.autoOpenSidebar
 */
config.autoOpenSidebar = function() {
    if(config.openSidebar == 1) {
        $('#back-btn').data('status',1);
    }

    if(config.openSidebar == 2) {
        config.openRightSidebar();
    }

    config.openSidebar = 0;
}


/**
 * App用户退出登陆
 * @method config.loginOut
 */
config.loginOut = function() {
    var url = config.pathUrl + "app_login.php";
    //var url = config.host + "/v3.6/app_login.php";
    var data = { type: 5 };
    $.ajax({type: 'get', url: url, data: data, dataType: 'json', async: false, success: function(result){
        if(result.status == 1) {
            window.location.href = config.pathUrl + "app_login.php";
        } else {
            tipsBox.createAlertBox('退出失败');
        }
    }});
}

/**
 * App系统升级
 * @method config.appUpgrade
 */
config.appUpgrade = function() {
    if(config.appid == 2) {
        cordova.getAppVersion.getVersionNumber(function (version) {
            config.appIsHasVersion = 1;
            if(version != app_cinfig.version) {
                tipsBox.AppUpload();
            }
        });

        setTimeout(function() {
            if(config.appIsHasVersion == 0) {
                tipsBox.AppUpload();
            }
        }, 3000);
    }
}

/**
 * 设置页面最低高度
 * @method config.setPageMinHeight
 */
config.setPageMinHeight = function() {
    var height = $(window).height();
    $('#view_page').css('minHeight',($(window).height() - 150)+"px" );
    share_info = home_share_info;
}

/**
 * 设置分享方案
 * @method config.setShareCopywriting
 * @param {String} title 分享标题
 * @param {String} content 分享简介
 * @param {String} img 分享图片
 * @param {String} url 分享链接
 */
config.setShareCopywriting = function(title, content, img, url) {
    share_info = {};
    share_info.title = title;
    share_info.content = content;
    share_info.img_url = img;
    share_info.url = url;
}

/**
 * 判断元素是否存在
 * @method config.elementIsExist
 * @param {String} id 元素id
 * @return {Boolen}
 */
config.elementIsExist = function (id) {
    var object = document.getElementById(id);
    if(object) {
        return true;
    } else {
        return false;
    }
}

/**
 * 过滤字符串
 * @method config.stripscript
 * @param {String} s
 */
config.stripscript = function(s) {
    var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）&mdash;—]")
    var rs = "";
    for (var i = 0; i < s.length; i++) {
        rs = rs + s.substr(i, 1).replace(pattern, '');
    }
    return rs;
}

/**
 * 控制返回按钮
 * @method window.onscroll
 */
window.onscroll = function () {
    config.scrollTop = document.documentElement.scrollTop || document.body.scrollTop;

    if(config.scrollTop > config.height) {
        var page = $('#page-mark').val();
        var display = $('#shop-cart-box').css('display');

        if((page == 'home' || page == 'special' || page == 'street') &&  display == 'none') {
            $('#retun-top-btn').show();
        }
    } else {
        $('#retun-top-btn').hide();
    }
    street.showGetVoucherBtn();
}

/**
 * 返回顶部
 * @method config.returnTop
 */
config.returnTop = function() {
    $("html,body").scrollTop(0);
    $('#retun-top-btn').hide();
}

/**
/**
 * 延时加载图片
 * @method config.lazyLoadImage
 * @param {Number} status
 */
config.lazyLoadImage = function(status) {
    //$("img.lazy").lazyload({threshold : 2000})
    //$("img.lazy").trigger("scroll");

    //设置大图图片父容器和子容器宽度
    var bdWidth = $('.tabBox').width();
    var bdheight = Math.ceil(bdWidth * 0.5);
    $('.tabBox ul').each(function() {
        var _this = $(this);
        _this.css('width',bdWidth*2 + 'px');
        _this.find('li').css({'width': bdWidth + 'px','height':bdheight + "px"});
        $('.switchLeft').css('line-height',bdheight + 'px');
        $('.switchRight').css('line-height',bdheight + 'px');
    });
    images_center.init('.lazy',bdWidth);
}

/**
 * 设置返回按钮
 * @method config.setBackBtn
 */
config.setBackBtn = function() {
    if(history.length <= 1) {
        console.log("adsds");
        window.location.href = config.pathUrl;
    } else {
        var back = $('#back-btn').data('status');
        if(back == 1) {
            var page = $('#page-mark').val();
            if(page == 'voucher' && $('#notice-return').val() == 1 && config.openSidebar != 1 ) {
                config.openSidebar = 0;
                window.history.back();
                return false;
            }
            switch (page) {
                case 'news':
                case 'email':
                case 'order':
                case 'voucher':
                case 'exchange':
                case 'recharge':
                case 'scan_course':
                case 'vip':
                case 'notice_list':
                    config.openSidebar = 2;
                    break;
                default :
                    config.openSidebar = 0;
                    break;
            }

            switch (page) {
                case 'zitiView':
                    //自提点详细信息页
                    select_area.backSendZiti(1);
                    return false;
                    break;
                case 'addressAddEidt':
                    //新增/编辑收货地址页
                    select_area.backSendZiti(0);
                    return false;
                    break;
                case 'bookingOrder':
                    //订悦订单列表返回到订悦首页
                    window.location.href = '#/booking';
                    return false;
                    break;
            }
            if(page == 'barcode' || page == 'bingo_code') {
                window.location.href = '#/scan_course';
                return false;
            }
            if(home.cur_product_class != '' && home.cur_product_class != undefined && home.cur_product_class != null) {
                if(home.cur_product_class == 'product_special') {
                    window.location.href = '#/product_special';
                } else {
                    window.location.href = '#/home/' + home.cur_product_class;
                }

            } else {
                //window.location.href = '../../../../Home';
                window.location.href = '.';
            }
            return false;
        }
        window.history.back();
    }
}

/**
 * 获得用户代理
 * @method config.getUserAgent
 */
config.getUserAgent = function() {
    var u = navigator.userAgent, app = navigator.appVersion;
    config.userAgent =  { //移动终端浏览器版本信息
        ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
        android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或uc浏览器
        iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
        iPad: u.indexOf('iPad') > -1 //是否iPad
    };

    if(config.userAgent.iPhone || config.userAgent.iPad || config.userAgent.ios) {
        config.isAppleDevice = 1;
    }
}


/**
 * 跳转
 * @method config.jumbUrl
 */
config.jumbUrl = function(url) {
    window.location.href = url;
    return false;
}

/**
 * App是否掉线
 * @method config.serve
 */
config.serve = function(status) {
    switch (status) {
        case 0:
            common.renderTpl("#serve-box",'common/common_serve',{});
            $('#serve-box').show();
            //tipsBox.tipsBoxCenter('.server-inner');
            break;
        case 1:
            $('#serve-box').hide();
            break;
    }
}

config.email_btn_status = 1;
config.email = function() {
    config.email_btn_status = 1;
    common.renderTpl("#app_content",'email',{});
    common.loaded(0);
}

config.email_submit = function() {
    if(config.email_btn_status == 0) {
        return false;
    }
    config.setEmailStatus(0);
    var reason = $('#reason').val();
    if(reason == '') {
        tipsBox.createAlertBox('请输入你的建议或吐槽～');
        config.setEmailStatus(1);
        return false;
    }
    var url = api_host+"/Api/Users/user_letter_add";
    var openid = user.userBase.bingo_openid;
    var data={
        bingo_access_token:openid
        ,bingo_openid:openid
        ,text:reason
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        if(result.status == 1) {
            $('#reason').val('');
            var tips = '提交成功!<br/>感谢你的建议或吐槽，宾哥会努力<br/>做得更好！再次祝你生活愉快!';
            tipsBox.createAlertBox(tips);
            $('.alert-wrap h3').addClass('tc');
            config.setEmailStatus(1);

        } else {
            config.setEmailStatus(0);
            tipsBox.createAlertBox(result.data);
        }
    }});
}

config.setEmailStatus = function(status) {
    if(status == 1) {
        config.email_btn_status = 1;
        $('#footer a').html('提交');
        $('#footer a').css('background','#6cbed8');
    }

    if(status == 0) {
        config.email_btn_status = 0;
        $('#footer a').html('提交中...');
        $('#footer a').css('background','#ccc');
    }

}

/*
 * 优化IOS滚动
 */
var browser = {
    versions: function () {
        var u = navigator.userAgent, app = navigator.appVersion;
        return { //移动终端浏览器版本信息
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
            android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或uc浏览器
            iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
            iPad: u.indexOf('iPad') > -1 //是否iPad
        };
    }()
}
function ios_scroll(){
    if (browser.versions.iPhone || browser.versions.iPad || browser.versions.ios) {
        $("#app").css("height","100% !important");
        //$("#app").css("minHeight",($(window).height() - 50)+"px !important");
        $("#app_content").css("height","100%");
        $("#app_content").css("overflow","scroll");

        $("#view_page").css("height","100% !important");
        $("#view_page").css("overflow","scroll");
        //$("#view_page").css("margin-bottom","100px");
        //$("#product_list").css("padding-bottom","60px");
    }
}

function ios_scroll_resert(){
    if (browser.versions.iPhone || browser.versions.iPad || browser.versions.ios) {
        $("#app").css("height","");
        $("#app_content").css("height","");
        $("#app_content").css("overflow","");

        $("#view_page").css("height","");
        $("#view_page").css("overflow","");
        $("#view_page").css("margin-bottom","");
        $("#product_list").css("padding-bottom","");
    }
}


/**
 * 宾哥见面礼
 */
var bingo = {}

bingo.meetMenu = function() {
    var url = api_host+"/Api/AfterSale/share_top_prize";
    var openid = user.userBase.bingo_openid;
    var data = { bingo_access_token: openid,bingo_openid: openid };
    $.ajax({type: 'post', url: url, data: data, dataType: 'json', async: false, success: function(result){
        if(user.userBase.is_bingo_meeting != "1") {
            window.location.href = '#/home';
            return false;
        }
        if(result.status !== '1') {
            tipsBox.createAlertBox(result.data);
            return false;
        }
        var html = template('bingo_meet_menu', result.data);
        $("#app_content").html(html);
        $('.footer-table tr td.center div').hide();
        $('.footer-table tr td.right div').hide();
        common.loaded(1);
    }});
}

bingo.meet = function() {
    var html = template('bingo_meet', {});
    $("#app_content").html(html);
    bingo.setBoxMinHeight('#bingo-meet-wrap');
    common.loaded(1);
}

bingo.voucher = function() {
    var url = api_host+"/Api/AfterSale/share_top_prize";
    var openid = user.userBase.bingo_openid;
    var data = { bingo_access_token: openid,bingo_openid: openid };
    $.ajax({type: 'post', url: url, data: data, dataType: 'json', async: false, success: function(result){
            var html = template('bingo_voucher', {});
            $("#app_content").html(html);
            common.loaded(1);
            if( result.status === '1' && result.data.task1_status !== '1'  ) {
                $('#bingo-voucher-btn').attr('href', '#/home');
            } else {
                $('#bingo-voucher-btn').attr('href', 'javascript:void(0);');
                $('#bingo-voucher-btn').addClass('deny-btn');
            }
        }
    });
}

bingo.prize = function() {
    var url = api_host+"/Api/AfterSale/share_top_prize";
    var openid = user.userBase.bingo_openid;
    var data = { bingo_access_token: openid,bingo_openid: openid };
    $.ajax({type: 'post', url: url, data: data, dataType: 'json', async: false, success: function(result){
            var html = template('bingo_prize', {});
            $("#app_content").html(html);
            bingo.setBoxMinHeight('#bingo-meet-wrap');
            common.loaded(1);
            if( result.status === '1' && result.data.task2_status !== '1'  ) {
                $('#bingo-prize-btn').attr('href', '#/shareset/' + result.data.order_id + '/myself');
            } else {
                $('#bingo-prize-btn').attr('href', 'javascript:void(0);');
                $('#bingo-prize-btn').addClass('deny-btn');
            }
        }
    });
}

bingo.invite = function() {
    var result = {};
    var host = window.location.host;
    if(host != 'test.bingofresh.com') {
        host = 'http://m.bingofresh.com';
    }  else {
        host = 'http://test.bingofresh.com';
    }
    result.img = host + "/User-show_user_qr_img.html?uid=" + user.userBase.id + "&t=" + user.userBase.vip_code + "&avatar=" + user.userBase.avatar;
    result.bingo_meet_prize = _privilege.bingo_meet_prize;
    var html = template('bingo_invite', result);
    $("#app_content").html(html);
    bingo.setBoxMinHeight('#privilege-wrap');
    
    common.loaded(1);
    document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() {WeixinJSBridge.call('showOptionMenu');});
    share_info = {
         "title":"缤果 - 全国领先生鲜购物平台",
         "img_url":"http://"+window.location.host+"/Public/Uploads/logo.jpg?v=2",
         "content":"",
         "url":  'http://'+window.location.host+result.img
    };
}

bingo.invite_rule = function() {
    var html = template('bingo_invite_rule', {});
    $("#app_content").html(html);
    common.loaded(1);
}

bingo.setBoxMinHeight = function(id) {
    var height = $(window).height();
    $(id).css('minHeight',height +'px');
}
/**
 *产品列表方法
 */
var home={};
home.product_view_data={};
home.position = '';
// home.homePage = 0;
home.banner = null;
home.productData = null;
home.productList = null;
home.cate_id = 0;
home.cur_product_class = ""; //当前商品选择的类型
home.first_product_class = "";
home.menuStatus = 0; //菜单状态
home.groupStatus = 0;
home.productItemList = null;
home.bannerItemList = null;
home.showProductTast = null;
home.allClass = null; //全部分类

/**
 * 首页初始化
 * @method home.init
 */
home.init = function() {
    common.loading();
    config.cart_init();
    navigation.menuType = 1;
    common.user_login(home.product_list_in_index);
    share_info = home_share_info; //分享内容
}

home.show_share_product=function(id,type){
    if(type == 'special') {
        product_special.show_v2(id)
    }
    if(type == 'normal') {
        home.get_share_product(id);
    }
}

home.get_share_product = function(pid) {
    var url=api_host+"/Api/Product/product_list";
    var openid=user.userBase.bingo_openid;
    if (openid==undefined || openid==null || openid.length==0){
        return false;
    }
    var data={
        bingo_access_token:openid
        ,bingo_openid:openid
        ,app_id:config.appid
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result) {
        var list = result.data;
        var len = list.product.length;
        for (var i = 0; i < len; i++) {
            product_list[list.product[i]["id"]] = list.product[i];
            if (pid==list.product[i]["pid"]){
                home.show_product_info(list.product[i]["id"],'normal');
                return false;
            }
        }
        window.location.href = '#/home';
    }});
}


/**
 * 加载产品列表数据
 * @method home.product_list_in_index
 */
home.product_list_in_index = function() {
    if(home.cur_product_class == ''  && home.menuStatus == 0) {
        home.getFirstClass();
    } else {
        home.show_product(0);
    }
}

/**
 * 改变类列表
 * @method home.changeProductClass
 * @param className
 */
home.changeProductClass = function(className) {

    //按钮点击统计
    var btnId = "";
    var btnName = "";
    switch(className){
        case "fruits":
            //水果
            btnId = "index_fruit";
            btnName = "水果分类";
            break;
        case "ingredient":
            //食材
            btnId = "index_food";
            btnName = "食材分类";
            break;
        case "snacks":
            //零食
            btnId = "index_snacks";
            btnName = "零食分类";
            break;
    };
    //统计点击次数
    common.buttonClikcStatistics("index",btnId,btnName);

    //$('#view_page').removeClass('slide-left-btn');
    clearInterval(home.showProductTast);
    home.cur_product_class = className;
    $('#header-menue-ui li a').removeClass('current');
    $('#menu-'+className).addClass('current');

    $("html,body").scrollTop(0);
    var html = template('loading', {});
    $("#view_page").html(html);
    //home.show_product(0);
    home.showProductTast = setTimeout("home.show_product(0)",3);

    //$("#slide-box-inner").css('marginLeft',config.width);
   // $("#slide-box-inner").animate({marginLeft:0+"px"});
    //$("#slide-box-inner").animate({left:0+"px"});
    //$('#view_page').css('width',config.width);
    //$('#slide-box').css('width',config.width);
    //$('#slide-box').css('height',config.height);
    //
    //$('#view_page').addClass('slide-menu');

    //setTimeout("home.removeSlideClass()",500);
}

/**
 * 点击及时送改变产品列表
 * @method home.headerMenuSend
 */
home.headerMenuSend = function(){
    home.cur_product_class = home.first_product_class;
    window.location.href = "#/home";
}

/**
 * 移除滑动效果
 * @method home.removeSlideClass
 */
home.removeSlideClass = function() {
    $('#view_page').removeClass('slide-menu');
}

/**
 * 获得产品分类
 * @method home.getFirstClass
 */
home.getFirstClass = function() {
    var branch_id = "";
    if(user.userBase.branch_id !== "") {
        branch_id = user.userBase.branch_id;
    }
    var url = api_host + "/Api/Product/league_nav";
    var openid = user.userBase.bingo_openid;
    var data = {
        bingo_access_token: openid
        ,bingo_openid: openid
        ,league_id: user.userBase.league_id
        ,branch_id: branch_id
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result) {
        if(result.status == 1) {
            if(result.data.nav != '') {
                for(var i in result.data.nav) {
                    if(home.cur_product_class == '') {
                        home.cur_product_class = result.data.nav[i].class_mark;
                    }
                    home.first_product_class = result.data.nav[i].class_mark;
                    break;
                }
            }
        }

        var url = '#/selectcity/';
        var city = result.data.city_league;
        if(city != ''  && city.league_id != '') {
            var url = '#/selectcity/' + city.city_name +'/1';
        }
        city.city_name = base.replaceString(city.city_name,'市','');
        city.city_url = url;
        result.data.city_league = city;
        navigation.menu = result.data;

        home.menuStatus = 1;
        home.product_list_in_index();
    }});
}

home.product_list_in_package = function(){
    home.show_product(1);
}

home.show_product = function(cate_id){
    if(_new_user_product_id == '') {
        home.get_public_config();
    }

    if(!common.isOwnEmpty(home.productList) && !common.isOwnEmpty(product_list) && home.first_product_class != '') {
        home.productList.product = home.getCurrentClassProduct(home.productItemList);
        home.productList.banner.top = home.getCurrentClassBanner(home.bannerItemList);
        home.show_product_tpl(home.productList);
        return false;
    }
    var data = home.get_product_param();
    $.ajax({type:'post',url:data.url,data:data.param,dataType: 'json',success:function(result){
        home.productData = result;
        home.cate_id = cate_id;
        home.productItemList = result.data.product;
        home.bannerItemList = result.data.banner.top;
        product_special.banner = home.getCurrentClassBanner(result.data.banner.top,'promotion');
        home.productList = home.get_product_data(result,cate_id);
        home.show_product_tpl(home.productList);
        home.areaTips();
    }});
};

/**
 * 用户所在不同地区提示
 * @method home.areaTips
 */
home.areaTips = function() {
    if(user.userBase.league_type == 'hezi' || user.userBase.league_type == 'BingoBox' || user.userBase.league_type == ''){
        //自提点和盒子不显示跨区提示
        return false;
    }
    if(config.isAppleDevice == 1) {
        common.weixin_geolocation(_point);
    } else { //andor机使用微信js定位会加载很慢,不停请求定位,出现卡机情况
        if (config.appid == 3) {
            common.weixin_geolocation(_point);
        } else {
            common.geolocation();
        }
    }
}

/**
 * 获得产品传递的参数
 * @returns {{url: string, param: {bingo_access_token: string, bingo_openid: string, league_id: *, branch_id: number}}}
 */
home.get_product_param = function() {
    var branch_id = 0;
    if(user.userBase.branch_id !== "") {
        branch_id = user.userBase.branch_id;
    }
    var openid = user.userBase.bingo_openid;
    var url = api_host + "/Api/Product/product_list";
    var param = {
        bingo_access_token: openid
        ,bingo_openid: openid
        ,league_id: user.userBase.league_id
        ,branch_id: branch_id
        ,app_id:config.appid
    };
    return { url: url, param: param};
}

/**
 * 渲染精选水果模版
 * @method home.show_product_tpl
 * @param {object} list
 */
home.show_product_tpl = function(list) {
    //重新给称重产品的价格赋值
    var data = list.product;
    var milkBanner = '<div class="font-zero"><img src="ui/images/header/milk_banner.png?v=2016021401" width="100%"/></div>';
    for(var i = 0; i< data.length; i++){
        data[i].price = product_weighing.countWeights('normal',data[i].price,data[i].weights,data[i].sales_spec);
    }

    list.product = home.getMilkData(list.product);
    if(config.elementIsExist('page-mark')  && home.productList != null) {
        var html = template('product_list', list);
        $("#view_page").html(html);
    } else {
        var html = template('product', list);
        $("#app_content").html(html);
    }

    if(home.cur_product_class == 'milk') {
        $('#product-box li.xiang-1').eq(0).prepend(milkBanner);
    }

    product_extend.set_product_voucher(list.give_voucher_info);

    home.setBanner(list.banner.top);
    broadcast.banner(list.video);
    //search.changeSearchModel(0);
    home.groupShowAppointClass();
    common.loaded(2);
    config.lazyLoadImage();
    product_extend.firstCome();
    // product_extend.newVersionCome();
    product_extend.friendCome();
    home.product_list_position();
    config.appUpgrade();
}

/**
 * 根据分类，显示团购在正常商品位置
 * @method home.firstClassShowGroup
 */
home.groupShowAppointClass = function() {
    if((!common.isOwnEmpty(product_group_list))) {
        var group_list = [];
        for(var i in product_group_list) {
            if(product_group_list[i].class_mark == home.cur_product_class) {
                group_list.push(product_group_list[i]);
            };
        }
        if((!common.isOwnEmpty(group_list))) {
            common.renderTpl('#group_list', 'product_group', { group_list: group_list });
            $('#group_list').css('margin-bottom','-13px');
            $('#group_list .product-item-box').addClass('group-item-border');
        }
    }
}

/**
 * 重设产品的数据的
 * @param {object} result
 * @param {string} cate_id 0:精选水果,1:礼盒水果
 * @return {object}
 */
home.get_product_data = function(result,cate_id) {
    var list = result.data;
    user.is_new_user = list.is_new_user; //是否是新用户
    list.product = home.getCurrentClassProduct(list.product);
    list.banner.top = home.getCurrentClassBanner(list.banner.top);


    if (cate_id == 0) { //团购
        list.product_group_list = home.set_group_data(list.groupbuy);
        list.small_group = home.set_small_group_data(list.small_group);
    } else {
        list.product_group_list = {};
    }

    list.img_v = _img_v; //图片时间戳
    list.GL_SELECTED = GL_SELECTED; //用户购物车里的水果
    home.banner = list.banner;
    //home.productList = list;
    return list;
}

/**
 * 获得当前类的banner
 * @method home.getCurrenBannerList
 * @param {Object} data
 * @param {String} currentCalss
 * @return {Object}
 */
home.getCurrentClassBanner = function(data, currentCalss) {
    if(data != '') {
        var classBanner = [];
        currentCalss =  (currentCalss  != undefined) ? currentCalss : home.cur_product_class;
        for(var i in data) {
            if(data[i].type_class == currentCalss) {
                classBanner.push(data[i]);
            }
        }
        return classBanner;
    }
    return '';
}

/**
 * 获得当前类的产品
 * @method home.getCurrentClassProduct
 * @param {Object} Data
 * @return {Object}
 */
home.getCurrentClassProduct = function(data) {
    if(data != '') {
        var classProduct = [];
        for (var i in data) {
            product_list[data[i]["id"]] = data[i];
            if(data[i].class_mark == home.cur_product_class) { //获得当前类产品
                classProduct.push(data[i]);
            }
        }
        return classProduct;
    }
    return '';
}

/**
 * 获得牛奶数据
 * @method home.getMilkData
 * @param {Object} Data
 * @return {Object}
 */
home.getMilkData = function(data) {
    if(data != '' && home.cur_product_class == 'milk') {
        var product = [],box = [];
        for (var i in data) {
            product_list[data[i]["id"]] = data[i];
            if(data[i].xiang == 0) {
                product.push(data[i]);
            } else {
                box.push(data[i]);
            }
        }

        for (var i in box) {
            product.push(box[i]);
        }

        return product;
    }
    return data;
}

/**
 * 重设团购的数据
 * @param {object} group
 * @return {object}
 */
home.set_group_data = function(group) {
    home.groupStatus = 1;
    for (var k in group) {
        if (_officeGroup != group[k]['id']) {
            if (group[k]["tuan_type"] == 2) {
                var tmp_strt = "";
                for (var kk in group[k]['rule']) {
                    if (group[k]['rule'][kk]["is_current"] == 1) {
                        group[k]["price"] = group[k]['rule'][kk]["price"];
                    }
                    if (kk > 0) {
                        tmp_strt += ",满" + group[k]['rule'][kk]["sum_start"] + "人价格降至" + group[k]['rule'][kk]["price"] + "元;";
                    }
                }
                group[k]["show_str"] = tmp_strt;
            }
            group[k]["ygendtime"] = (group[k]["ygendtime"].charAt(0) == '-') ? '团购已结束' : group[k]["ygendtime"] + '后结束';
            group[k]["price"] = group[k]["tuan_type"] == 1 ? group[k]["ygprice"] : group[k]["price"];
            group[k]["num"] = 1;
            group[k]['kucun'] = parseInt(group[k]['kucun']);
            group[k]['ygcount'] = parseInt(group[k]['ygcount']);
            group[k]['jian_maxcount'] = parseInt(group[k]['jian_maxcount']);
            product_group_list[group[k]["id"]] = group[k];
        }
    }
    return product_group_list;
}

/**
 * 设置微团购数据
 * @method home.set_small_group_data
 * @param {Object} data
 * @return {Object}
 */
home.set_small_group_data = function(data) {
    var host = window.location.host;
    var url = '';
    if(host == 'test.bingofresh.com') {
        // url = 'http://test.bingofresh.com//actives-black_gallon-index-event_id-';
        url = 'http://test.bingofresh.com//';
    } else {
        // url = 'http://m.bingofresh.com//actives-black_gallon-index-event_id-';
        url = 'http://m.bingofresh.com//';
    }
    for(var i in data) {
        if(data[i]['pin_mark'] == 'turntable_group_list'){
            url += 'actives-black_gallon_turntable-index-event_id-';
        }else{
            url += 'actives-black_gallon-index-event_id-';
        }
        data[i]['url'] = url + data[i]['id'] + '.html';
        product_small_group_list[i] = data[i];
    }
    return product_small_group_list;
}

/**
 * 设置banner
 * @param {object} data
 * @return {void}
 */
home.banner_data = null;
home.setBanner = function(data) {
    if(common.isOwnEmpty(data)) {
        return false;
    }
    common.renderTpl('#top-banner-box','product/product_banner',{data: data});
    $('#top-banner-box').show();

}

home.bannerJumb = function(url) {
    window.location.href = url;
}

/**
 * 用户通过水果详细页面，点返回，回到用户指定点水果banner
 */
home.product_list_position = function() {
    if(home.position != '' && $(home.position).offset() != null ) {
        var top = $(home.position).offset().top - 70;
        /*
        if(navigator.userAgent.match(/Android/i)) {
            $("body,html").animate({ scrollTop: top },0);
            $("body,html").scrollTop(top);
        } else {
           $("#view_page").animate({ scrollTop: top },0);
           $("#view_page").scrollTop(top);
        }*/
        $("body,html").animate({ scrollTop: top },0);
        $("body,html").scrollTop(top);
    }
}


home.microGroup = function() {
    var uid=user.userBase.bingo_openid;
     var url= _bingo_host+"/actives-ActiveData-count_info2.html?user_id="+uid;
     $.ajax({type:'get',url:url,dataType:'json',success:function(result){
         //{"is_join":1,"group_buy_num":0,"group_sku_num":0,"my_price":"49.90","my_group_num":"10"}
         if (result.is_join==0){
             $("#micro_group_info").html('<p>参团人数：<span id="group_buy_num">'+result.group_buy_num+'</span></p> <p>共售出数量：<span id="group_sku_num">'+result.group_sku_num+'</span></p>');
         }else{
             $("#micro_group_info").html('<p>你的团人数：<span id="group_buy_num">'+result.my_group_num+'</span></p> <p>当前价格：<span id="group_sku_num">'+result.my_price+'</span></p>');

             $("#micro_group_href").attr("href","http://m.bingofresh.com/actives-MicroGroup-index.html?gid="+result.gid);
         }

    }});
}

//获得公共配置
home.get_public_config = function() {
    var url=api_host+"/Api/BaseService/get_public_config";
    var openid=user.userBase.bingo_openid;
    if (openid==undefined || openid==null || openid.length==0){
        return false;
    }
    var data={ bingo_access_token:openid };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        _new_user_product_id = result.data.new_user_share_product_id;

    }});
}

home.show_my_cart = function() { //显示用户购物车

    if($("#cart_num").html() == 0){
        return false;
    }
    if( $("#shop-cart-box").html() != '') {
        home.my_cart_hide();
        return false;
    }

    //按钮点击统计
    common.buttonClikcStatistics("index","index_myCar","购物车");

    var j = 0;
    var cart_info = {};
    var buycar = getCookie('buycar');
    var special_car = getCookie('special_car');
    var weighingLen = product_weighing.productData.length;
    if(buycar == null && special_car == null && weighingLen == 0) {
        home.my_cart_hide();
        return false;
    }
    //如果存在称重产品
    if(weighingLen > 0){
        var weighingData = product_weighing.productData;
        for (var i = 0; i < weighingLen; i++) {
            cart_info[j++] = { id:weighingData[i].id, pxid:weighingData[i].pxid,  title:weighingData[i].name,  num:1, thu_img:weighingData[i].thu_img, price:weighingData[i].price, type:'weighing' };
        }
    }
    if(buycar != null) {
        var all_p = buycar.split("|");
        if(all_p.length > 0 && all_p[0] != "") {
            for (var i = 0; i < all_p.length; i++) {
                var p = all_p[i].split(',');
                if (p.length < 4){
                    break;
                }
                var id = p[0];
                var product=product_list[id];
                var item_total_price = product_list[id].price*Number(p[2]);
                if(item_total_price > parseInt(item_total_price)){
                    item_total_price = item_total_price.toFixed(2);
                }
                if (product!=undefined){
                    cart_info[j++] = { id:product_list[id].id,  title:product_list[id].title,  num:Number(p[2]), thu_img:product_list[id].thu_img, price:item_total_price, type:'normal' };
                }
            }
        }
    }

    if(special_car != null) {
        var all_p = special_car.split("|");
        if(all_p.length > 0 && all_p[0] != "") {
            for (var i = 0; i < all_p.length; i++) {
                var p = all_p[i].split(',');
                if (p.length < 4){
                    break;
                }
                var id = p[0];
                var product=product_special_list[id];
                var item_total_price = product_special_list[id].price*Number(p[2]);
                if(item_total_price > parseInt(item_total_price)){
                    item_total_price = item_total_price.toFixed(2);
                }
                if (product!=undefined){
                    cart_info[j++] = { id:product_special_list[id].id,  title:product_special_list[id].title,  num:Number(p[2]), thu_img:product_special_list[id].thu_img,price:item_total_price, type:'special' };
                }
            }
        }
    }

    var data= {data : cart_info };

    var html = template('cart_info', data);
    $("#shop-cart-box").html(html);
    $("#shop-cart-box").show();
    var height = $('.shop-cart-box').height();
    var width = $('.shop-cart-box dl').width();
    $('.shop-cart-box dl img').css('height',width+'px');
    // $('.shop-cart-mask').show();
    var windowHeight = $(window).height() - 100;
    $('.shop-cart-box').css('max-height',parseInt(windowHeight)+'px') ;

    if(height > parseInt(windowHeight)) {
        $('.shop-cart-bottom-tips').show();
        base.preventPenetration();   //禁止底层滚动
    }
    $('#footer').css('height','60px');
    $('#footer').css('background','#fff');
    $('.shopping-cart-box').css('margin-top','0');
    $('#retun-top-btn').hide();
    street.setCartBtnColor();
}
home.my_cart_hide = function() {

    if($('.shop-cart-box').html() == ""){
        return false;
    }

    if($('html,body').hasClass('penetration-in')) {
        base.recoverPenetration();     //恢复底层滚动
    }

    $("#shop-cart-box").html('');
    $("#shop-cart-box").hide();
    $('#footer').attr('style','');
    $('.shopping-cart-box').css('margin-top','-10px');
    // $('.shop-cart-mask').hide();
}
home.show_my_cart_hide = function() {
    $("#shop-cart-box").html('');
    $("#shop-cart-box").hide();
}
//购买指定产品加1 +1
function plusBtn(id,event){
    var p=product_list[id];
    if(user.is_new_user == 0 && product_list[id]['for_new_user'] == 1) {
        tipsBox.createAlertBox(product_list[id]['title']+'是新用户专享哦~');
        return false;
    }
    if(!common.isVip() && product_list[id]['for_level'] == 1){
        tipsBox.createAlertBox(product_list[id]['title'] + '是会员专享哦~');
        return false;
    }

    //新用户专享
    if(parseInt(p.is_allow_buy) != 1 ) {
        tipsBox.createAlertBox(p.title+'产品限量购买，不能再多了');
        return false;
    }
    if (user.userBase.user_type == 0 && p.pid==_new_user_product_id){
        tipsBox.createConfirmBox('关注缤果水果才能购买该产品,现在去关注?','voucherview.go_voucher',0,'确定');
        return false;
    }

    if (user.is_new_user==0 && p.pid==_new_user_product_id){
        tipsBox.createAlertBox('新用户才能购买此款产品，新用户指之前没有在缤果下过订单的用户');
        return false;
    } else {
        var ret=do_plus(p);
        if (ret==false){
            return false;
        }

        tongji();
        show_user_buy(p,event);

        if(event == "cartinfo"){     //用户购物车指定产品加1 +1c处理
            var item_price = $("#item-price-"+p.id).text();
            var item_num =  Number($("#item-num-"+p.id).text()) + 1;
            var item_total_price = parseFloat(item_price) + parseFloat(p.price);
            if(item_total_price > parseInt(item_total_price)){
                item_total_price = item_total_price.toFixed(2);
            }
            $("#item-price-"+p.id).text(item_total_price);
            $("#item-num-"+p.id).text(item_num);
        }
    }
}

//购买指定产品减1 -1
function subtractBtn(id,event){
    var p=product_list[id];
    do_subtract(p);
    tongji();
    show_user_buy(p);
    if(event == "cartinfo"){     //用户购物车指定产品减1 -1处理
        var item_price = $("#item-price-"+p.id).text();
        var item_num =  Number($("#item-num-"+p.id).text()) - 1;
        var item_total_price = parseFloat(item_price) - parseFloat(p.price);
        if(item_num == 0){
            $("#iteminfo-"+p.id).remove();       //移除该商品
            if($("#cart_num").html() == 0){     //当没有产品时关闭清空用户购物车
                home.my_cart_hide();
            }
            var windowHeight = $(window).height() - 100;
            var height = $('.shop-cart-box').height();
            //不需要滚动时隐藏到底提示
            if(height < parseInt(windowHeight) && $('.shop-cart-bottom-tips').css('display') == 'block') {
                $('.shop-cart-bottom-tips').hide();
            }
        }else{
            if(item_total_price > parseInt(item_total_price)){
                item_total_price = item_total_price.toFixed(2);
            }
            $("#item-price-"+p.id).text(item_total_price);
            $("#item-num-"+p.id).text(item_num);
        }
    }

}

function do_plus(p){
    //console.log(p.restriction);
    var checkNum = p.restriction!=undefined?p.restriction:0;

    if (p==undefined){
        return false;
    }
    if (p.kucun < 1) {
        return false;
    }
    if (p.kucun-p.num <= 0){
        alertBox('.alert-box',p.title+'库存不足,您可以选购别的商品哦');
        return false;
    }
    if(checkNum>0 && p.num>=checkNum) {
        alertBox('.alert-box',p.title+'商品限量购买，不能再多了');
        //$scope.list[index].limit = 1;
        return false;
    }
    if (p.num==undefined || p.num==0){
        p.num=1;
    }else{
        p.num++;
    }

    operateCart(p);
    //home.show_my_cart_hide();
    return true;
}

function do_subtract(p){
    if (p==undefined){
        return false;
    }
    if (p.num==undefined || p.num<=0){
        return false;
    }else{
        p.num--;
    }
    operateCart(p);
    return true;
}

/**
 * 载入cookies中的商品
 * @method load_cookies
 */
function load_cookies(){
    var buycar = getCookie('buycar');
    //console.log(buycar);
    if(buycar != null) {
        var all_p = buycar.split("|");
        if(all_p.length > 0 && all_p[0] != "") {
            for (var i = 0; i < all_p.length; i++) {
                var p = all_p[i].split(',');
                if (p.length<4){
                    break;
                }
                var id=p[0];
                var product=product_list[id];
                if (product!=undefined){
                    product.num=Number(p[2]);
                    show_user_buy(product,"load");
                }
            }
            tongji();
        }
    }
    //显示用户已选择的称重产品
    product_weighing.showUserBuy();
}
//在详情页面载入cookies中信息
function load_cookies_view(pid){
    var buycar = getCookie('buycar');
    if(buycar != null) {
        var all_p = buycar.split("|");
        if(all_p.length > 0 && all_p[0] != "") {
            for (var i = 0; i < all_p.length; i++) {
                var p = all_p[i].split(',');
                if (p.length<4){
                    break;
                }
                var id=p[0];
                if (pid==id){
                    home.product_view_data.num=Number(p[2]);
                    home.product_view_data.total_fee=(Number(p[2])*Number(p[3]));
                    $("#view_subtotal").text(Number(p[2])*Number(p[3]));
                    $("#view_buy_num").text(p[2]);
                    $(".minus").removeClass("forbidden");
                }
            }
        }
    }
}
//写购物车cookies
function operateCart(product_item) {
    //console.log("ssss");
    var id=product_item.id;
    var title=product_item.title;
    var num=product_item.num;
    var price=product_item.price;
    var isPre=product_item.isPre;

    if(isPre) {
        in_buy_car_yugou(id, title, num, price);
    } else {
        in_buy_car(id, title, num, price);
    }

    actives.discountOpera('0');
}

function tongji(){
    common.tongji();
}

/**
 * 产品详情初始化
 * @param {int} id 水果id
 * @param {int} type 0:精选水果，1:礼盒水果
 */
home.show_product_info = function(id,type){
    switch(type) {
        case 'normal':
            if(common.isOwnEmpty(product_list)){
                var data = home.get_product_param();
                $.ajax({type:'post',url:data.url,data:data.param,dataType: 'json',success:function(result) {
                    home.productData = result;
                    home.cate_id = 0;
                    home.get_product_data(result, 0);
                    home.show_product_item_tpl(id, type);
                }});
            } else {
                home.show_product_item_tpl(id, type);
            }
            break;
        case 'groupbuy':
            if(common.isOwnEmpty(product_list)){
                var data = home.get_product_param();
                $.ajax({type:'post',url:data.url,data:data.param,dataType: 'json',success:function(result) {
                    home.productData = result;
                    home.cate_id = 0;
                    home.get_product_data(result, 0);
                    home.groupOauthLogin(id,type);
                }});
            } else {
                home.groupIsExist(id, type);
            }

            break;
        default:
            home.show_product_item_tpl(id, type);
            break;
    }
};

/**
 * 设置商品详情返回
 * @method home.product_info_return
 * @param {String} type
 */
home.product_info_return = function(type) {
    switch(type) {
        case 'normal':
            if (home.cur_product_class != '') {
                $('#return-btn').attr('href', '#/home/' + home.cur_product_class);
            } else {
                $('#return-btn').attr('href', '#/home');
            }
            break;
        case 'groupbuy':


            break;
        default:
            //home.show_product_item_tpl(id, type);
            break;
    }
}

/**
 * 显示水果的模板
 * @param id
 * @param type
 */
home.show_product_item_tpl = function(id, type) {
    if(_new_user_product_id == '') {
        home.get_public_config();
    }
    home.product_view_data={num:0,total_fee:0};
    var url=api_host+"/Api/Product/product_view";
    var openid=user.userBase.bingo_openid;
    if (openid==undefined || openid==null || openid.length==0){
        return false;
    }
    var buycar = getCookie('buycar');
    var data={
        bingo_access_token:openid
        ,bingo_openid:openid
        ,id:id
        ,type:type
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        if(result.data == '') {
            window.location.href = config.pathUrl;
            return false;
        }

        result.data.save = 0;
        result.data.price = parseFloat(result.data.price);
        if(parseInt(result.data.shichangjia) > 0) {
            result.data.save = result.data.shichangjia - result.data.price;
        } else if(result.data.save <= 0 &&  parseInt(result.data.original_price) > 0) {
            result.data.save = result.data.original_price - result.data.price;
        }

        if(result.data.save > parseInt(result.data.save)) {
            result.data.save = parseFloat(result.data.save).toFixed(1);
        }

        result.data.img_v = _img_v;

        var width = $(window).width();
        result.data.windowWidth = width;
        result.data.wrapWidth = width * result.data.img.length;
        result.data.liHight = width / 2;

        result.data.price = product_weighing.countWeights(type,result.data.price,result.data.weights,result.data.sales_spec);

        common.renderTpl("#app_content",'product_view',result.data);
        $("#product-info-content").html(result.data.content);
        $("#product-info-content img").css('width','100%');
        product_extend.user_focus();

        //导入图片轮播
        // imgSlider.init(result.data.img,'imagesSlider');

        common.loaded(0);
        load_cookies();
        load_cookies_view(id);
        home.position = '#'+type+'-'+id;
        home.product_info_return(type);
        home.setProductConfig(id, result.data.title, result.data.thu_img, type);
        home.getSinglProcutClass(id,type);
    }});
}


/**
 * 获得单一商品的类型,显示提示
 * @param Number id  商品id
 * @param String type 商品类型
 */
home.getSinglProcutClass = function(id, type) {
    var show_tips = 0;
    switch (type) {
        case 'groupbuy':
            show_tips = (product_group_list[id].class_mark == 'fruits') ? 1 : 0;
            break;
        case 'normal': {
            show_tips = (product_list[id].class_mark == 'fruits') ? 1 : 0;
        }
    }

    if(show_tips == 1) {
        $('.product-info-tips').show();
    }
}

/**
 * 团购详细购买按钮
 * @method home.groupIntoBuyBtn
 * @param {Number} id 团购产品id
 * @returns {Null}
 */
home.groupIntoBuyBtn = function(id) {
    var groupInfo = home.productData.data.groupbuy;    //所有团购
    var this_ygcount = 0;      //当前团购商品的团购数
    var id_arr = [];      //所有团购的id
    var ygcount_arr = [];       //所有团购的团购数
    $.each(groupInfo, function(i){
        id_arr.push(groupInfo[i].id);
        ygcount_arr.push(groupInfo[i].ygcount);
    });
    var arr_num = $.inArray(id, id_arr);
    if(arr_num >= 0){
        this_ygcount = ygcount_arr[arr_num];
    }

    if(product_group_list[id].is_allow_buy == 0) {
        $('#footer-product-info').html('<a href="javascript:void(0);" id="footer-group-btn"  class="ft-color bd-color" onclick="tipsBox.createAlertBox(\'你已参团\')" ><span>已参团</span><span id="groupbuy_ygcount">' + this_ygcount + '人已参团</span></a>');
    } else if ( product_group_list[id].tuan_show_count <= product_group_list[id].ygcount) {
        $('#footer-product-info').html('<a href="javascript:void(0);" id="footer-group-btn"  class="ft-color bd-color" onclick="tipsBox.createAlertBox(\'团购产品卖光了\')" ><span>卖光了</span><span id="groupbuy_ygcount">' + this_ygcount + '人已参团</span></a>');
    } else  if(product_group_list[id].status == 0) {
        $('#footer-product-info').html('<a href="javascript:void(0);" id="footer-group-btn"  class="ft-color bd-color" style="background: #ccc;" onclick="tipsBox.createAlertBox(\'团购已结束\')" ><span>团购结束</span><span id="groupbuy_ygcount">' + this_ygcount + '人已参团</span></a>');
    } else {
        var title = product_group_list[id].title;
        var price = product_group_list[id].price;
        $('#footer-product-info').html('<a href="javascript:void(0);" id="footer-group-btn"  class="ft-color bd-color" onclick="cart_group.cart(\''+id+'\',\''+title+'\',\''+price+'\')" ><span>马上参团</span><span id="groupbuy_ygcount">' + this_ygcount + '人已参团</span></a>');
    }

    if(history.length <= 1) {
        $('#return-btn').attr('href','#/product_special');
    } else {
        $('#return-btn').attr('href','javascript:history.back();');
    }
    home.position = '#group-item-'+id;
}

/**
 * 团购用户参团，需要登陆
 * @method home.groupOauthLogin
 * @param {Number} id 商品id
 * @param {String} type 商品类型
 */
home.groupOauthLogin = function (id, type) {
    common.setCookie('come_from','#/product_view/groupbuy/'+id,365);
    var url = api_host + "/Api/Users/oauth_login";
    var openid = user.userBase.bingo_openid;
    var data = {
        bingo_secret : 'fb92390dd7c59c3fcb4fcce4801aadecb79f2e4a'
        ,bingo_appid : config.appid
        ,oauth_type : 4
        ,oauth_openid : openid
    };
    $.ajax({type : 'post', url : url ,data : data, dataType : 'json', success:function(result){
        if(result.status == 1) {
            user.islogin = 1;
            user.userBase = result.data;
            user.userBase.bingo_openid = openid;
            if(user.userBase.league_id == '' || user.userBase.league_id == 0 ) {
                window.location.href="./location.php?league_id=0&city_code=0&open_id="+openid+"&slatitude="+result.data.slatitude+"&slongitude="+result.data.slongitude;
            } else {
                for(var k in user.userBase.city_config) {
                    select_area.city_list[user.userBase.city_config[k]['code']] = user.userBase.city_config[k]['name'];
                }
                home.groupIsExist(id, type);
            }
        } else {
            tipsBox.createAlertBox(result.data);
        }
    }});
}

/**
 * 设置产品详情显示配置
 * @method home.setProductConfig
 * @param {String} type 产品类型
 * @param {Number} id 产品id
 * @param {String} title 产品标题
 * @param {String} img 产品小图
 */
home.setProductConfig = function(id, title, img, type) {
    var share_host = "";
    var app_shere = '';
    switch(type) {
        case 'special':
            $('.product-assessment-video').hide();
            $('#product-cut-notice').hide();
            $('#product-type').val('special');
            navigation.setShoppingCartSize();
            share_host = config.pathUrl + "/?go=product_share/special/"+product_special_list[id]["pid"];
            app_shere = '&id='+id+'&type=special';
            break;
        case 'groupbuy':
            $('#product-info-param').hide();
            $('.product-assessment-video').hide();
            $('#product-mask-line').hide();
            $('#product-type').val('groupbuy');
            $('.fruit_detail_price').hide();
            home.groupIntoBuyBtn(id);
            navigation.setShoppingCartSize();
            //share_host = config.pathUrl + "/home.php#/product_view/groupbuy/"+id;
            share_host = config.pathUrl + "/?go=product_view/groupbuy/"+id;
            app_shere = '&id='+id+'&type=groupbuy';
            break;
        case 'normal':
            $('#product-type').val('normal');
            $('#product-info-opera').show();
            $('#footer-product-btn').attr('style','');
            $('#footer-product-btn').css('padding','0 6%');
            $('#footer-product-btn').css('display','inline-block');
            share_host = config.pathUrl + "/?go=product_share/normal/"+product_list[id]["pid"];
            app_shere = '&id='+id+'&type=normal';
            break;
    }
    app_shere = config.appShareUrl +'?page=product_view&token='+user.userBase.bingo_openid + app_shere;
    share_app.operate(_is_app, '上缤果,买'+title+'。缤果,全国领先的优质生鲜购物平台', '向你推荐来自缤果的优质商品', img, app_shere);
    config.setShareCopywriting(title, '向你推荐来自缤果的优质商品', img, share_host);
}

/**
 * 团购是否存在
 * @method home.groupIsExist
 * @param {Number} id 产品id
 * @pram {String} type 产品类型
 */
home.groupIsExist = function(id, type) {
    if(common.isOwnEmpty(product_group_list[id])){
        common.delCookie('come_from');
        window.location.href = config.pathUrl;
        return false;
    }
    common.delCookie('come_from');
    home.show_product_item_tpl(id, type);
}


//产品详情页面增加
home.product_view_plusBtn=function(id,price,kucun){
    if (home.product_view_data.num==0){
        $(".minus").removeClass("forbidden");
    }
    if (kucun-home.product_view_data.num==0){
        alertBox('.alert-box','库存不足,您可以选购别的商品哦');
        return false;
    }
    if (plusBtn(id)!=false){
        home.product_view_data.num++;
        home.product_view_data.total_fee=home.product_view_data.num*price;
        $("#view_subtotal").text(home.product_view_data.total_fee.toFixed(2));
        $("#view_buy_num").text(home.product_view_data.num);
    }
};

/**
 * 产品详情页面减少
 */
home.product_view_plusBtn_subtractBtn=function(id,price){
    if (home.product_view_data.num==0){
        return false;
    }
    if (home.product_view_data.num==1){
        $(".minus").addClass("forbidden");
    }
    home.product_view_data.num--;
    home.product_view_data.total_fee=home.product_view_data.num*price;
    $("#view_subtotal").text((home.product_view_data.total_fee).toFixed(2));
    $("#view_buy_num").text(home.product_view_data.num);
    subtractBtn(id);
};

/*
 *产品详情页降价通知
 * @method home.cut_notice
 * @param {String} id 产品id
 */
home.cut_notice = function(id,price){
    if(!base.checkBtnLock()){    //防止重复提交
        return false;
    }
    var cutBtn = $("#product-cut-notice");
    if(cutBtn.hasClass('current')){    //取消通知
        tipsBox.createConfirmBox('你正在取消降价通知，这款商品降价时，将不再给你发通知，是否确认取消？','home.cancel_cut_notice',id,'是','否');
    }else{      //添加通知
        var url=api_host+"/Api/Product/downprice_register";
        var openid=user.userBase.bingo_openid;
        if (openid==undefined || openid==null || openid.length==0){
            return false;
        }
        var data={
            bingo_access_token: openid
            ,bingo_openid: openid
            ,bingo_appid: config.appid
            ,oauth_type: 1
            ,id: id
            ,price: price
            ,register: 1
        };
        $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
            if(result.status == 1) {
                base.clearBtnLock();     //解锁按钮
                cutBtn.addClass('current');
                tipsBox.createAlertBox('这款商品降价，宾哥会立即通知你哦，去商城逛逛别的吧，祝你购物愉快！');
            } else {
                tipsBox.createAlertBox(result.data);
            }
        }});

        //按钮点击统计
        common.buttonClikcStatistics("view","view_cut","降价通知");
    }
}

/*
 * 产品详情页确定取消降价通知
 * @method home.cancel_cut_notice
 * @param {String} id 产品id
 */
home.cancel_cut_notice = function(id){
    var url=api_host+"/Api/Product/downprice_register";
    var openid=user.userBase.bingo_openid;
    if (openid==undefined || openid==null || openid.length==0){
        return false;
    }
    var data={
        bingo_access_token: openid
        ,bingo_openid: openid
        ,bingo_appid: config.appid
        ,oauth_type:1
        ,id: id
        ,register: 0
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        if(result.status == 1) {
            tipsBox.hideTipsBox();
            $("#product-cut-notice").removeClass('current');
            base.clearBtnLock();     //解锁按钮
        } else {
            tipsBox.createAlertBox(result.data);
        }
    }});
}

/**
 * 产品详情页播放开箱视频
 * @method home.product_unpack
 * @param {String} src 视频链接
 */
home.product_unpack = function(src){
    if(src == "" || src == undefined){
        tipsBox.createAlertBox('这款产品暂时没有开箱视频～宾哥会尽快补充，感谢你的支持');
        return false;
    }
    video.playVideoBnt(src,"open");     //播放视频

    //按钮点击统计
    common.buttonClikcStatistics("view","view_openVideo","开箱视频");
}

/*
home.synchronous_normal_fruit_kucun = function(data,lid) { //同步正常水果库量
    special_socket.emit('synchronous normal fruit kucun',data,lid);
}*/
home.update_normal_fruit_kucun = function(data,lid) { //同步正常水果库存
     var product_page = $('#product_page').val();
    if(product_page == 1 && user.userBase.league_id == lid) { //判断用户所在的加盟商，更新正常页面的上的数据
        var buycar_arr = {};
        if(getCookie('buycar') != null) {
            var buycar = getCookie('buycar').split('|');
            for (var i = 0; i < buycar.length; i++) {
                var tmp = buycar[i].split(',');
                buycar_arr[tmp[0]] = 1;
            }
        }
        for(var k in data) {
            product_list[data[k].id].kucun = data[k].last_kucun;
            if(product_list[data[k].id].kucun > 0 && product_list[data[k].id].kucun < 4) {
                document.getElementById('lows-tock-'+data[k].id).innerHTML = '<span>库存紧张</span>';
            } else {
                document.getElementById('lows-tock-'+data[k].id).innerHTML = '';
            }
            if(buycar_arr[data[k].id] != 1 && parseInt(product_list[data[k].id].kucun) <= 0) {
                var btn_str = '<div class="product-notice">';
                btn_str += '<div class="product-notice-inner">';
                if(product_list[data[k].id].tongzhi == 0) {
                     btn_str += '<div class="product-notice-no" onclick="onNotice($(this),\''+data[k].pid+'\',\''+data[k].title+'\',\''+data[k].id+'\')">上架<br/>通知我</div>';
                } else {
                     btn_str += '<div class="product-notice-has">等待<br/>上线通知</div>';
                }
                btn_str += '<p>暂时缺货</p></div></div>';
                document.getElementById('product-opera-inner-'+data[k].id).innerHTML= btn_str;
             }
        }
    }
}

/**
 * 设置产品封面图片高度
 * @method home.setCoverSize
 */
home.setCoverSize = function() {
    var model = 0;
    var width = $(window).width() - 16;
    var height = parseInt(parseFloat(width) * 0.453) + 'px';
    var width2 = parseInt(width * 0.35) > 135 ? 135 : parseInt(width * 0.35);
    $('.product-box li').each(function(){
        model = $(this).data('model');
        switch(parseInt(model)) {
            case 0:
                $('.product-item-header img.lazy').css('height',height);
                break;
            case 1:
                $('.product-item-table tr td:first-child').css('width',width2+"px");
                $('.product-item-table tr td:first-child img').css('height',width2+"px");
                break;
        }
    });
}


//产品列表显示用户购买情况
function show_user_buy(product_item,event){
    var id=product_item.id;
    var item="product-item-"+id;
    if(product_item.totalPrice != undefined){
        var subtotal = base.setNumberDecimals(product_item.totalPrice);    //写入称重产品总价格
    }else{
        var subtotal = base.setNumberDecimals(product_item.num * product_item.price);
    }
    $("#item_num_"+id).text(product_item.num);
    $("#item_subtotal_"+id).text(subtotal);
    if (product_item.num==1 || event=="load"){
        $("#"+item+" .product-item-box").addClass("selected");
        $("#"+item+" .street-item-box").addClass("selected");
        $("#product-buy-btn-"+id).hide();
        $("#product-buy-oprea-"+id).show();
        if (event!=undefined && event!="load"){
            animateCart(product_item.thu_img,event);
        }
    }else if(product_item.num<=0){
        $("#"+item+" .product-item-box").removeClass("selected");
        $("#"+item+" .street-item-box").removeClass("selected");
        $("#product-buy-btn-"+id).show();
        $("#product-buy-oprea-"+id).hide();
    }
}



//缺货登记
function onNotice(_this, pid, title, id) {
    var url=api_host+"/Api/Product/stockout_register";
    var openid=user.userBase.bingo_openid;
    if (openid==undefined || openid==null || openid.length==0){
        return false;
    }
    var data={
        bingo_access_token:openid
        ,bingo_openid:openid
        ,bingo_appid:config.appid
        ,pid:pid
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        if(result.status == 1) {
            _this.html("<dl><dt>等待</dt><dd>通知</dd></dl>");
            _this.css('backgroundColor','#fcdb00;');
            _this.removeAttr('onclick');
            product_list[id].tongzhi = 1;
            tipsBox.createAlertBox('商品上架后，宾哥会立即通知你，祝你购物愉快~');
        } else {
            tipsBox.createAlertBox(result.data);
        }
    }});

    //按钮点击统计
    common.buttonClikcStatistics("index","index_notice","上架通知");
}

var animateAction;
//购买时动画效果
function animateCart(imgSrc,event,pageX,pageY) {
    if (!imgSrc)
        return;
    var event = event || window.event;
    var pos = {};
    var menuPos = {};
    var product = $('#cart-img');
    var img = $('#cart-img');
    var cart = $('#cart');
    var menu = $('#footer');

    /*
    if(!$('#cart').is(":animated") || !$('#cart-img').is(":animated")  ){ //判断元素是否处于动画状态,zepto不支持
        $('#cart').stop();
        $('#cart-img').stop();
        clearInterval(animateAction);
    }*/

    img.attr('src', imgSrc);
    if(pageX == undefined || pageX == null || pageX == ''){
        pos.x = event.pageX - img.width() / 2;
        pos.y = event.pageY;
    }else{
        pos.x = pageX - img.width() / 2;
        pos.y = parseInt(pageY);
    }

    product.css({
        'left': pos.x,
        'top': pos.y
    });
    menuPos.x = menu.offset().left;
    menuPos.y = menu.offset().top;
    product.show().animate({
        left: menu.width() / 2 - img.width() / 2 - ((cart.width() - img.width()) / 2),
        //left: (menu.width() - img.width()) / 2 + ((cart.width() - img.width()))  ,
        top: menuPos.y - (cart.width() + img.height()) - 30
    }, 600, function() {
        $(this).animate({
            top: menuPos.y - cart.width() + 10
        }, 200, function() {
            product.hide();
            animateAction = setTimeout(function() {
                cart.animate({
                    top: menuPos.y
                }, 300, function() {
                    cart.hide();
                });
            }, 100);

        });
    })

    cart.show().css({
        left: menu.width() / 2 - cart.width() / 2,
        //left: (menu.width()  - cart.width()) / 2,
        top: menuPos.y
    }).animate({
        top: menuPos.y  - cart.width()
    }, 200);
}

/**
 * 大图切换、加载
 * @method home.switchPicture
 * @param {String} _this DOM标签
 * @param {Number} _sta 图片滚动方向-1右滚/1左滚
 * @param {String} id 产品id
 * @param {String} type 产品类型
 */
home.switchPicture = function(_this,_sta,id,type){
    //检查按钮是否解锁
    if($(_this).data('lock') == 'lock'){
        return false;
    }

    var marginLeft = parseFloat($(_this + ' ul').css('margin-left').replace("px",""));
    var status = $(_this).data('status');
    if (marginLeft == 0 && status == 0) {    //处于第一张，而且没有加载过图片
        //检查产品对象，拿到当前产品的大图
        var data_number = [];
        var data_type = [];
        switch(type){
            case 'group':
                var product_data = home.productData.data.groupbuy;
                break;
            case 'small_group':
                var product_data = home.productData.data.small_group;
                break;
            case 'normal':
                var product_data = home.productData.data.product;
                break;
            default:
                var product_data = home.productData.data.product;
                break;
        }
        $.each(product_data, function(i){
            data_number.push(i);
            data_type.push(product_data[i].id);
        });
        var arr_num = $.inArray(id, data_type);
        if( arr_num >= 0){
            var data_type_arrnum = data_number[arr_num];
        }
        var product_imgs = product_data[data_type_arrnum].img;

        //调用图片切换程序
        imgSlider.switchPicture(id,_this,_sta,product_imgs);
    }else{
        //调用图片切换程序
        imgSlider.switchPicture(id,_this,_sta);
    }

    //按钮点击统计
    var page = $('#page-mark').val();
    if(page == 'home'){
        common.buttonClikcStatistics("index","index_switch","大图切换");
    }else if(page == 'product-info'){
        common.buttonClikcStatistics("view","view_switch","大图切换");
    }
}
var images_center = {};
/**
 * 图片居中初始化
 * @method images_center.init
 * @param {String} element 元素
 * @param {Float} rate 比率
 */
images_center.init = function(element, width, rate) {
    var bdWidth = width;
    //设置产品图片高度
    $(element).each(function() {
        var _this = $(this);
        var width = _this.width();
        var height = 0;
        var model = _this.data('model');
        // console.log(width);
        switch(model) {
            case 1:
                height = width > 135 ? 135 : width;
                _this.parent().css('height',height);
                break;
            case 2: //长: 480 高: 200
                height = Math.ceil(width * 0.416);
                break;
            default: //长:480 高: 216
                // height = Math.ceil(width * 0.45);
                height = Math.ceil(bdWidth * 0.5);
                _this.parents(".tabBox").css('height',height);
                break;
        }
    });
}


/**
 * 设置图片偏移量
 * @param {Number} original 原始大小
 * @param {Number} current  当前大小
 * @returns {number}
 */
images_center.setImageOffset = function(original, current) {
    if(original > current ) {
        return parseInt((original - current) / 2);
    } else if(original < current) {
        return parseInt((current - original) / 2) * -1;
    }
    return 0;

    // if(original > current ) {
    //     return parseInt((original - current) / 2) * -1;
    // } else if(original < current) {
    //     return parseInt((current - original) / 2);
    // }
    // return 0;
}

/**
 * 设置图片显示居中
 * @method setImagesCenter
 * @param {Object} _this 当前对象
 * @param {String} src 图片路径
 */
images_center.setImagesCenter = function(_this, src) {
    var _parent = _this.parent();
    var width = _parent.width();
    var height = _parent.height();
    $("<img/>").attr("src", src).load(function() {
        var realWidth = this.width;
        var realHeight = this.height;
        var rate = realHeight / realWidth;

        var showHeight = parseInt(width * rate);
        var marginTop = images_center.setImageOffset(height,showHeight);
        _this.css('width','100%');
        _this.css('marginTop',marginTop);

        // var showWidth = parseInt(height / rate);
        // var marginLeft = images_center.setImageOffset(showWidth,width);
        // _this.css({'width': showWidth + 'px','height': height + 'px', 'margin-left': marginLeft + 'px'});

    });
}

/**
 * 图片切换程序，可以通过入口调用
 * DOM结构必须为div>ul>li>img，其中li是切换项
 */
var imgSlider = {};

/**
 * 图片切换程序入口
 * @method imgSlider.init
 * @param {Array} data 图片数据
 * @param {String} dimId 图片容器，必须是id
 */
imgSlider.init = function(data,domId){
	//所有的图片数据
	var list = data;

	//初始化Slider实例
	new imgSlider.Slider({
	 dom : document.getElementById(domId),
	 list : list
	});
}

/**
 * 图片切换程序的构造函数
 * @param {Object} opts
 */
imgSlider.Slider = function(opts){
	//构造函数需要的参数
	this.wrap = opts.dom;      //绑定的DOM元素
	this.list = opts.list;      //图片数据

	this.init();       //一些初始化的数据
	this.renderDOM();     //渲染DOM
	this.bindDOM();    //绑定监听DOM事件
}

/**
 * 向构造函数添加方法init()。数据初始化
 */
imgSlider.Slider.prototype.init = function() {
	this.scaleW = window.innerWidth;    //设置图片容器的宽度
	this.scaleH = window.innerWidth/2;    //设置图片容器的高度
	this.idx = 0;      //设置初始的索引值(页数)
};

/**
 * 向构造函数添加方法renderDOM()。根据数据渲染DOM
 */
imgSlider.Slider.prototype.renderDOM = function(){
	var wrap = this.wrap;    //整个容器
	var data = this.list;    //图片数据
	var len = data.length;    //数据长度

	this.outer = document.createElement('ul');    //图片的UL容器

	for(var i = 0; i < len; i++){
		var li = document.createElement('li');
		var item = data[i];

		//设置每一项li的宽高
		li.style.width = window.innerWidth +'px';
        li.style.height = window.innerWidth/2 +'px';

        //定义3D转换
		li.style.webkitTransform = 'translate3d('+ i*this.scaleW +'px, 0, 0)';

		//设置每一项li的html
        li.innerHTML = '<img height="'+ this.scaleH +'" src="'+ item +'">';

        //向UL里添加li
		this.outer.appendChild(li);
	}

	//UL的宽度和画布宽度一致
	this.outer.style.cssText = 'width:' + this.scaleW +'px';

	wrap.style.height = this.scaleH + 'px';
	wrap.appendChild(this.outer);
};

/**
 * 向构造函数添加方法goIndex()。跳转页数(n可以是任一页)
 */
imgSlider.Slider.prototype.goIndex = function(n){
	var idx = this.idx;
	var lis = this.outer.getElementsByTagName('li');
	var len = lis.length;
	var cidx;

	//如果传数字 2,3 之类可以使得直接滑动到该索引
	if(typeof n == 'number'){
		cidx = idx;
	//如果是传字符则为索引的变化
	}else if(typeof n == 'string'){
		cidx = idx + n*1;
	}

	//当索引右超出
	if(cidx > len-1){
		cidx = len - 1;
	//当索引左超出
	}else if(cidx < 0){
		cidx = 0;
	}

	//保留当前索引值
	this.idx = cidx;

	//改变过渡的方式，从无动画变为有动画
	lis[cidx].style.webkitTransition = '-webkit-transform 0.2s ease-out';
	lis[cidx-1] && (lis[cidx-1].style.webkitTransition = '-webkit-transform 0.2s ease-out');
	lis[cidx+1] && (lis[cidx+1].style.webkitTransition = '-webkit-transform 0.2s ease-out');

	//改变动画后所应该的位移值
	lis[cidx].style.webkitTransform = 'translate3d(0, 0, 0)';
	lis[cidx-1] && (lis[cidx-1].style.webkitTransform = 'translate3d(-'+ this.scaleW +'px, 0, 0)');
	lis[cidx+1] && (lis[cidx+1].style.webkitTransform = 'translate3d('+ this.scaleW +'px, 0, 0)');
};

/**
 * 向构造函数添加方法bindDOM。绑定 DOM 事件,分别监听手指的按下，拖动，以及释放事件
 */
imgSlider.Slider.prototype.bindDOM = function(){
	var self = this;
	var scaleW = self.scaleW;
	var outer = self.outer;
	var len = self.list.length;

	//手指按下的处理事件
	var startHandler = function(evt){
		self.startTime = new Date() * 1;    //记录刚刚开始按下的时间
		self.startX = evt.touches[0].pageX;     //记录手指按下的坐标
		self.offsetX = 0;    //清除偏移量

		//事件对象
		var target = evt.target;
		while(target.nodeName != 'LI' && target.nodeName != 'BODY'){
			target = target.parentNode;
		}
		self.target = target;
	};

	//手指移动的处理事件
	var moveHandler = function(evt){
		evt.preventDefault();    //阻止浏览器默认行为

		self.offsetX = evt.targetTouches[0].pageX - self.startX;    //计算手指的偏移量
		var lis = outer.getElementsByTagName('li');     //找到容器下所有的li
		var i = self.idx - 1;      //起始索引
		var m = i + 3;     //结束索引

		//最小化改变DOM属性
		for(i; i < m; i++){
			lis[i] && (lis[i].style.webkitTransition = '-webkit-transform 0s ease-out');
			lis[i] && (lis[i].style.webkitTransform = 'translate3d('+ ((i-self.idx)*self.scaleW + self.offsetX) +'px, 0, 0)');
		}
	};

	//手指抬起的处理事件
	var endHandler = function(evt){
		evt.preventDefault();    //阻止浏览器默认行为

		var boundary = scaleW/6;    //边界翻页的值，容器的宽度除6
		var endTime = new Date() * 1;    //手指抬起的时间值
		var lis = outer.getElementsByTagName('li');    //找到容器下所有的li

		//当手指移动时间超过300ms 的时候，按位移算
		if(endTime - self.startTime > 300){
			if(self.offsetX >= boundary){    //上一页
				self.goIndex('-1');
			}else if(self.offsetX < 0 && self.offsetX < -boundary){     //下一页
				self.goIndex('+1');
			}else{      //停在当前页
				self.goIndex('0');
			}
		}else{
			//优化，快速移动也能使得翻页
			if(self.offsetX > 50){      //右拖拽超过50单位，上一页
				self.goIndex('-1');
			}else if(self.offsetX < -50){     //左拖拽超过50单位，下一页
				self.goIndex('+1');
			}else{     //停在当前页
				self.goIndex('0');
			}
		}
	};

	//绑定事件监听
	outer.addEventListener('touchstart', startHandler);
	outer.addEventListener('touchmove', moveHandler);
	outer.addEventListener('touchend', endHandler);
};

/**
 * 图片切换以及图片加载，不带触摸推拽效果
 * 如果不需要图片加载功能，图片容器_this的属性data-status设置为1
 * @method home.switchPicture
 * @param {String} id 标识符
 * @param {String} _this DOM标签
 * @param {Number} _sta 图片滚动方向-1右滚/1左滚
 * @param {Array} data 图片数据
 */
imgSlider.switchPicture = function(id,_this,_sta,data){
    //检查按钮是否解锁
    if($(_this).data('lock') == 'lock'){
        return false;
    }
    $(_this).data('lock','lock');
    var status = $(_this).data('status');
    var widthItem = $(_this).width();
    var heightItem = $(_this).height();
    var marginLeft = parseFloat($(_this + ' ul').css('margin-left').replace("px",""));
    if(_sta == -1){    //右滚
        if (marginLeft == 0 && status == 0) {    //处于第一张，而且没有加载过图片，暂时无法点击按钮
            var plus = parseFloat(widthItem * _sta);
            $(_this).data('status',1);     //设置当前商品大图状态为已渲染
            var html = "";
            //跳过第一张
            for(var i = 1,len = data.length; i < len; i++){
                html += '<li style="width:' + widthItem + 'px;height:' + heightItem + 'px"><img src="' + data[i] + '" class="loadenPic" data-model="0"/></li>';
            }
            var ulWidth = widthItem * parseFloat(data.length);
            $(_this + ' ul').css('width', ulWidth + 'px');
            //延迟1秒假加载
            setTimeout(function(){
            	$(_this + ' ul li').last().replaceWith(html);
            },1000);
            // $(_this + ' ul').append(html);
            $(_this).data('lock','unlock');
            $(_this + ' ul').animate({marginLeft:plus+"px"},200);
            //控制左右切换的按钮显示隐藏
	    	$("#switchLeft" + id).show();
            if(data.length === 2){
            	$("#switchRight" + id).hide();
            }
            return false;
        }else{    //已经加载完毕
            var len = $(_this + ' ul li').length;
            var awith = (parseInt(widthItem) - marginLeft)/len;
            if(awith >= widthItem){     //如果是最后一张
                $(_this).data('lock','unlock');
                return false;
            }
            var plus = parseFloat(marginLeft + _sta*widthItem);
        }
    }else{     //左滚
        if(marginLeft == 0){
            $(_this).data('lock','unlock');      //第一张
            return false
        }
        var plus = parseFloat(marginLeft+_sta*widthItem);
    }
    $(_this + ' ul').animate({marginLeft:plus+"px"},100);
    $(_this).data('lock','unlock');

    //控制左右切换的按钮显示隐藏
    var bPlus = parseFloat(widthItem) + _sta*plus;
    var wrapWidth = $(_this).find('ul').width();
    //第一张
    if(plus == 0){
    	$("#switchLeft" + id).hide();
    }
    //第二张
    if(parseFloat(bPlus) == widthItem * 2){
    	$("#switchLeft" + id).show();
    }
    //最后一张
    if(bPlus == wrapWidth){
    	$("#switchRight" + id).hide();
    }
    //倒数第二张
    if(parseFloat(wrapWidth) + _sta * plus == widthItem * 2){
    	$("#switchRight" + id).show();
    }
}
/**
 * 我的个人中心
 * 初始化个人中心数据
 *
 * @author keepsilent
 * @version 1.0.0
 */
var mid_autumn = (function(){
    var order_remark = '';
    var jsonData = {};

    /**
     * 中秋初始化
     */
    var init = function() {
        $('#gifts-mothed').show();
    }

    var windowShow = function() {
        $("html,body").scrollTop(0);
        $('.cart-footer').hide();
        $('#app-header').hide();
        $("#buy_cart_div").hide();
        $('.snap-content').addClass('user_addr_admin_bottom');

        $("#mid-autumn-window").show();
        $('#mid-autumn-window').css('min-height', ($(window).height() - 50) + "px");
        common.renderTpl("#mid-autumn-window","./mid_autumn/window",mid_autumn.jsonData);
    }

    var windowHide = function() {
        tipsBox.hideTipsBox();
        $('.cart-footer').show();
        $('#app-header').show();
        $("#buy_cart_div").show();
        $("#mid-autumn-window").hide();
        var top = parseInt($('#mid-autumn-box').offset().top) + 50;
        $('.snap-content').removeClass('user_addr_admin_bottom');
        $("html,body").scrollTop(top);
        var youWishes = mid_autumn.jsonData.wishes;
        if(mid_autumn.jsonData.wishes == '') {
            youWishes = '赠'+mid_autumn.jsonData.recipient+',祝中秋快乐!';
        }
        $('#you-wishes').html(youWishes);
    }

    var sureSubmit = function() {
        var data = {
            'wishes':$('#mid-autumn-wishes').val(),
            'recipient':$('#mid-autumn-recipient').val(),
            'giver':$('#mid-autumn-giver').val(),
            'tel':$('#mid-autumn-tel').val()
        }

        var tips = {
            'wishes':'请输入你的中秋祝福语',
            'recipient':'请填写收礼人的姓名',
            'giver':'请填写你的姓名',
            'tel':'请填写你的联系方式'
        }

        for(var i in data) {
            if(data[i] == '' && i != 'wishes') {
                tipsBox.createAlertBox(tips[i]);
                return false;
            }
        }


        var send_type = $('input[name="send_type"]:checked').val();
        if(parseInt(send_type) == 2) {
            $('#ziti_tel').val(data.tel);
        }

        mid_autumn.jsonData = data;



        if(data['wishes'] == '') {
            var tips = '你还未填写对好友的中秋祝福寄语，是否继续提交？';
            tipsBox.createConfirmBox(tips,'mid_autumn.windowHide','','是','否')
            return false
        }

        mid_autumn.windowHide();
    }

    /**
     * 中秋是否送礼
     * @param status
     */
    var sendMothed = function(status) {
        var gift_type = $('input[name="gifts"]:checked').val();
        var send_type = $('input[name="send_type"]:checked').val();
        $('#mid-autumn-box').hide();
        $('#address-manage tr td:first-child').html('收货<br/>信息');
        $('#new-address').html('请选择收货地址');
        switch (parseInt(gift_type)) {
            case 1: //自提
                break;
            case 2: //中秋送礼
                if(status == 1) { //显示提示
                    showTip(1);
                }

                if(send_type == 2) {
                    $('#ziti_tel').val('');
                }

                if(send_type == 1) {
                    $('#addr1').val('');
                    $('#addr3').val('');
                    $('#address-manage tr td:first-child').html('收礼<br/>信息');
                    $('#new-address').show().html('请填写收礼人的姓名及联系方式');
                    $('#has-default-address').hide();
                }
                $('#mid-autumn-box').show();
                break;
        }

        $('#mid-autumn-bag').hide();
        $('.shopping-bag-select-btn').hide();
        if(gift_type == 2) {
            $('#mid-autumn-bag').show();
        } else {
            $('.shopping-bag-select-btn').show();
        }
    }

    /**
     * 提交订单检查数据
     * @returns {boolean}
     */
    var submitCheck = function() {
        mid_autumn.order_remark = '';
        if(_minAutumnSwitch == 0) {
            return true;
        }

        var gift_type = $('input[name="gifts"]:checked').val();
        var send_type = $('input[name="send_type"]:checked').val();
        if(parseInt(gift_type) == 1) {
             mid_autumn.order_remark = {'method': 1 };
            return true;
        }

        if(common.isOwnEmpty(mid_autumn.jsonData)) {
            tipsBox.createAlertBox('请填写中秋祝福语');
            return false;
        }

        mid_autumn.order_remark = mid_autumn.jsonData;
        mid_autumn.order_remark.method = 2;
        return true;
    }

    /**
     * 显示中秋提示
     * @param status
     */
    var showTip = function(status) {
        if(status == 0) {
            $('#mid-autumn-tip').hide();
            base.recoverPenetration();
        } else {
            $('#mid-autumn-tip').show();
            var height = $('#mid-autumn-overflow').height();
            var maxHeight = config.height * 0.6;
            if(height > maxHeight) {
                $('#mid-autumn-overflow').css('height',maxHeight);
                $('#mid-autumn-overflow').css('overflow-y','scroll');
            }
            base.preventPenetration();
            tipsBox.tipsBoxCenter('#mid-autumn-tip div.mid-autumn-tip-inner');

        }
    }

    /**
     * 生成礼盒模板
     * @param data
     */
    var createBagTpl = function(data) {
        cart_bag.bag_data = data;
        common.renderTpl("#mid-autumn-bag","./mid_autumn/index",{data:setPackbagPosition(data.packbag)});

        var width = (config.width - 20) * 0.99 / 3 * 0.8;
        $('#mid-autumn-bag img.bag-img').css('width',width);
        $('#mid-autumn-bag img.bag-img').css('height',width);
        $('#mid-autumn-bag div.bag-img-wrap').css('width',width+2);
        $('#mid-autumn-bag div.bag-img-wrap').css('height',width+2);
    }

    /**
     * 设置礼盒的位置
     * @param {Object} data 数据
     * @returns {*}
     */
    var setPackbagPosition = function(data) {
        var j = 1;
        for(var i in data) {
            switch (j) {
                case  1:
                    data[i].position = 'left';
                    break;
                case 2:
                    data[i].position = 'center';
                    break;
                case 3:
                    data[i].position = 'right';
                    break;
            }

            if(j % 3 == 0) {
                j = 1;
            } else {
                j++;
            }
        }

        return data;
    }

    return {
        init:init,
        showTip:showTip,
        jsonData:jsonData,
        order_remark:order_remark,
        windowShow:windowShow,
        windowHide:windowHide,
        submitCheck:submitCheck,
        sureSubmit:sureSubmit,
        sendMothed:sendMothed,
        createBagTpl:createBagTpl
    };
})();

$('#mid-autumn-method input').live('click',function() {
    $(this).parent().parent().find('label.round').removeClass('current');
    $(this).parent().find('label.round').addClass('current');
});
/**
 * 导航
 */
var navigation = {};
navigation.menu = null;
// navigation.menuStatus = 0;
navigation.menuType = 0;

/**
 * 导航路由
 * @method navigation.route
 * @reutn {Null}
 */
navigation.route = function() {
    var page = $('#page-mark').val();
    switch (page) {
        case 'home': //首页
            navigation.menuMode();
            navigation.shoppingCart();
            //home.setCoverSize();
            break;
        case 'special': //省钱
            navigation.menuMode();
            navigation.shoppingCart();
            //home.setCoverSize();
            break;
        case 'part': //选择地区
            navigation.partMode();
            break;
        case 'street': //街
            street.header();
            navigation.shoppingCart();
            street.footer();
            break;
        case 'product-info': //产品详细
            common.renderTpl('#app-footer-main','footer_product',{});
            break;
        case 'booking':   //订悦
            navigation.menuMode();
            break;
        default :
            navigation.commonStyle();
            break;
    }
    if(config.elementIsExist('app-header-main')) {
        FastClick.attach(document.getElementById('app-header-main'));
    }
    //$('#user-no-focus').hide();
    //$('#view_page').css('paddingTop','0px');
    //$('#user-no-focus-height').css('height','0px');
}

/**
 * 导航通用样式
 * @metehod navigation.commonStyle
 * @param {String} mark 输入page
 */
navigation.commonStyle = function(mark) {
    if(mark == undefined || mark == null || mark == ''){
        var page = $('#page-mark').val();
    }else{
        var page = mark;
    }
    common.renderTpl('#app-header-main','header/header_common', {});
    switch (page) {
        case 'order':
            common.renderTpl('#header-common-main','order/order_menu', {});
            break;
        case 'voucher': //优惠券
            common.renderTpl('#header-common-main','voucher/voucher_menu', {});
            break;
        case 'voucher-view':
            navigation.simpleStyle('代金券详情');
            common.renderTpl('#app-footer-main','voucher/voucher_footer', {});
            break;
        case 'appraise':
            navigation.simpleStyle('评价');
            // if($('#is_complaint').val() != 1) {
            //     navigation.commonFooterTpl('提交评价','','aftersale.appraise_deliveryman()');
            // }
            break;
        case 'appraise-entrance':
            navigation.simpleStyle('订单已完成');
            navigation.commonFooterTpl('去缤果商城','#/home');
            break;
        case 'courier_complaint':
            navigation.simpleStyle('我要投诉');
            navigation.commonFooterTpl('我要投诉','','aftersale.complaint_deliveryman()');
            break;
        case 'thank':
            navigation.simpleStyle('返回');
            navigation.commonFooterTpl('去缤果商城','#/home');
            break;
        case 'complaint_success':
            navigation.simpleStyle('投诉成功');
            navigation.commonFooterTpl('去缤果商城','#/home');
            break;
        case 'exchange':
            common.renderTpl('#header-common-main',"exchange_menu",{});
            break;
        case 'barcode':
            navigation.simpleStyle('返回');
            break;
        case 'bingo_code':
            navigation.simpleStyle('查询失败');
            navigation.commonFooterTpl('再扫一次','','scan_code.scan_btn()');
            break;
        case 'scan_course':
            navigation.simpleStyle('商品扫一扫');
            navigation.commonFooterTpl('立即去扫一扫','','scan_code.scan_btn()');
            break;
        case 'return_exchange':
            navigation.simpleStyle('退货换货');
            break;
        case 'return_goods':
            navigation.simpleStyle('退货换货');
            break;
        case 'feedback':
            navigation.simpleStyle('退货换货');
            navigation.commonFooterTpl('查看我的余额','#/recharge');
            break;
        case 'share':
            navigation.simpleStyle('晒单');
            break;
        case 'news':
            navigation.simpleStyle('使用帮助');
            navigation.commonFooterTpl('去缤果商城','#/home');
            break;
        case 'privilege':
            navigation.simpleStyle('返回');
            break;
        case 'notice_list':
            navigation.simpleStyle('我的通知消息');
            break;
        case 'notice_post':
            navigation.simpleStyle('缤果文章');
            break;
        case 'cart':
            navigation.simpleStyle('返回购物');
            $('#back-btn').attr('javascript:cart.returnBtn();');
            break;
        case 'bookingCart':
            navigation.simpleStyle('订悦');
            // $('#back-btn').attr('href','#/booking');
            break;
        case 'bookingAddress':
            navigation.simpleStyle('收货地址');
            $('#back-btn').attr('href','javascript:booking.addressReturnCart();');
            break;
        case 'bookingPay':
            navigation.simpleStyle('订单支付');
            $('#back-btn').attr('href','javascript:booking.addressReturnCart();');
            break;
        case 'bookingOrder':
            common.renderTpl('#header-common-main','booking/booking_order_menu', {});
            $('#back-btn').data('status',1);
            break;
        case 'bookingUnsubscribe':
            navigation.simpleStyle('我要退订');
            break
        case 'aliPay':
            navigation.simpleStyle('订单详情');
            navigation.commonFooterTpl('立即支付','','cart.aliPay_pay()');
            break;
        case 'balance':
            navigation.simpleStyle('订单详情');
            navigation.commonFooterTpl('立即支付','','recharge.rightNowPayOrder()');
            break;
        case 'email':
            navigation.simpleStyle('宾哥信箱');
            navigation.commonFooterTpl('提交','','config.email_submit()');
            break;
        case 'vip':
            navigation.simpleStyle('缤果会员');
            $('#back-btn').data('status',1);
            break;
        case 'getVip':
            navigation.simpleStyle('成为缤果会员');
            break;
        case 'broadcast':
            navigation.simpleStyle('缤果直播间');
            //navigation.commonFooterTpl('去缤果商城','#/home');
            break;
        case 'zitiView':
            navigation.simpleStyle('自提点详细信息');
            $('#back-btn').data('status',1);
            break;
        case 'addressAddEidt':
            navigation.simpleStyle('收货地址');
            $('#back-btn').data('status',1);
            break;

    }
    navigation.setHeaderHeight();
}

/**
 * 控制返回页面
 * @method navigation.returnControl
 */
navigation.returnControl = function() {
    var page = $('#page-mark').val();
    switch (page) {
        case 'news':
        case 'order':
        case 'voucher':
        case 'exchange':
        case 'recharge':
        case 'barcode':
        case 'bingo_code':
        case 'scan_course':
            $('#back-btn').data('status',1);
            break;
    }
}

/**
 * 简单通用样式
 * @metehod navigation.simpleStyle
 */
navigation.simpleStyle = function(title) {
    var html = '<span class="ft-color">'+title+'</span>';
    $('#header-common-main').html(html);
    $('#header-common-main').addClass('tl')
    $('#header-common-main').removeClass('tc');
    $('.header-common-inner td:last-child').removeAttr('onclick');
    $('.header-common-inner td:last-child').html('');
}

/**
 * 通用底部数据
 * @method navigation.commonFooterTpl
 * @param {String} title 标题
 * @param {String} Url 链接
 * @param {String} clickEvnet 点击事件
 * @param {String} classStr 类字符
 */
navigation.commonFooterTpl = function(title, url, clickEvnet, classStr) {
    var url = (url != '' && url != undefined) ? url : 'javascript:void(0);';
    var clickEvnet = (clickEvnet != '' && clickEvnet != undefined) ? 'onclick='+clickEvnet : '';
    var classStr = (classStr != '' && classStr != undefined) ? classStr : 'common-footer bd-style';
    if(url == '#/home') {
        if(home.first_product_class != '') {
            url = '#/home/'+home.first_product_class;
        } else {
            url = ".";
        }
    }
    var data = { 'title': title, 'classStr': classStr, 'url': url ,'click': clickEvnet };
    common.renderTpl('#app-footer-main','common/common_footer',data);
}


/**
 * 购物车
 * @method navigation.shoppingCart
 */
navigation.shoppingCart = function() {
    var html = template('footer_shopping', {});
    $('#app-footer-main').html(html);
    navigation.setShoppingCartSize();
}

/**
 * 设置购物车大小
 * @method navigation.setShoppingCartSize
 */
navigation.setShoppingCartSize = function() {
    if(config.elementIsExist('shopping-cart-box')) {
        $('#shopping-cart-box').attr('style','');
        var width = $('#shopping-cart-box').width();
        $('#shopping-cart-box').css('width',width +'px');
        $('#shopping-cart-box').css('display','block');
        if($(".shop-cart-mask").css("display") == "block"){
            $('#shopping-cart-box').css('margin-top','0px');
        }
    }

    if(config.elementIsExist('footer-product-btn')) {
        if($('#product-type').val() == 'normal') {
            return false;
        }
        navigation.setProductInfoBtn('footer-product-btn');
    }
    if(config.elementIsExist('footer-group-btn')) {
        if($('#product-type').val() == 'normal') {
            return false;
        }
        navigation.setProductInfoBtn('footer-group-btn');
    }
}

/**
 * 设置产品详情购物车按钮大小
 * @method navigation.setProductInfoBtn
 * @param {String} id
 */
navigation.setProductInfoBtn = function(id) {
    $('#'+id).attr('style','');
    var width = $('#'+id).width();
    $('#'+id).css('padding','0 6%');
    $('#'+id).css('margin','0 auto');
    $('#'+id).css('width',width +'px');
    $('#'+id).css('display','block');
}


/**
 * 地区模式导航
 * @method navigation.partMode
 */
navigation.partMode = function() {
    if(common.isZitiTest()) {
        common.renderTpl("#app-header-main","header/header_part",{});
        if(user.userBase.league_id == undefined || user.userBase.league_id == '' || user.userBase.league_id == 0 || (user.userBase.league_type == "fendian" && user.userBase.default_address == "")){
            //新用户或者数据异常的用户隐藏返回按钮，必须要选择一个地址
            $('#selectCityBack').hide();
        }
    } else {
        common.renderTpl("#app-header-main","header_part",{});
    }

    var marginLeft = $('#header-part-city').width() / 2 * -1;
    $('#header-part-city').css('marginLeft', marginLeft + 'px');
    navigation.setHeaderHeight();
}

/**
 * 菜单模式导航
 * @method navigation.menuMode
 */
navigation.menuMode = function() {
    // if(common.isOwnEmpty(navigation.menu) && navigation.menuStatus == 0 ) {
    if(navigation.menu == null){
        navigation.getProductClass();
    } else {
        var pageMark = $('#page-mark').val();
        var userBase = user.userBase;
        var messages = parseFloat(userBase.none_all_count);
        navigation.menu.menuType = navigation.menuType;

        navigation.menu.booking = 0;
        if(pageMark == 'booking') {
            //订悦
            navigation.menu.booking = 1;
            navigation.menu.bookingNav = booking.bookingNav;
        }

        navigation.menu.messages = {
            status : messages > 0 ? 1 : 0,
            count : messages > 99 ? '...' : messages,
            css : messages > 9 ? 'more' : 'less'
        }

        if(common.isZitiTest()) {
            navigation.menu.league_type = userBase.league_type;
            if(userBase.league_type == "fendian"){
                //配送
                var areaName = (userBase.default_address.area_name == undefined) ? "" : userBase.default_address.area_name;
                var addr_doorplate = (userBase.default_address.addr_doorplate == null || userBase.default_address.addr_doorplate == undefined) ? "" : userBase.default_address.addr_doorplate;
                navigation.menu.address = areaName + userBase.default_address.address + addr_doorplate;
                navigation.menu.short_name = userBase.short_name;
            }else{
                //自提
                navigation.menu.address = userBase.display_name;
                navigation.menu.short_name = userBase.area_name;
            }
            common.renderTpl('#app-header-main','header/header_top',navigation.menu);
        } else {
            common.renderTpl('#app-header-main','header/header_main',navigation.menu);
            var partWidth = $('#current-part dl').width() + 20;
            $('#current-part').css('width', partWidth + 'px');
        }
        var children =  $('#header-menue-ui').children().length;
        if(children >= 2) {
            var width = $('#header-menue-ui').width();
            $('#header-menue-ui li').css('width', parseInt(width / children) + 'px');
            if(home.cur_product_class == '') {
                home.cur_product_class = $('#header-menue-ui li').data('class');
            }

            switch (pageMark) {
                case 'home':
                    $('#menu-'+home.cur_product_class).addClass('current');
                    break;
                case 'special':
                    $('#menu-special').addClass('current');
                    break;
                case 'booking':
                    if(common.isZitiTest()) {
                        $('#menu-booking').addClass('current');
                    } else {
                        $('#menu-' + booking.navClass).addClass('current');
                    }
                    break;
            }
        }
        if(pageMark == 'booking' && children < 2){
            $('#header-menu-bottom').hide();
        }

        notice.control('menu');
        navigation.setHeaderHeight();

        var width = config.width - 135;
        $('#partBoxRightAddress').css('width',width + 'px');
    }
}

/**
 * 获得产品类型
 * @method navigation.getProductClass
 */
navigation.getProductClass = function() {
    var branch_id = "";
    if(user.userBase.branch_id !== "") {
        branch_id = user.userBase.branch_id;
    }
    var url = api_host + "/Api/Product/league_nav";
    var openid = user.userBase.bingo_openid;
    var data = {
        bingo_access_token: openid
        ,bingo_openid: openid
        ,league_id: user.userBase.league_id
        ,branch_id: branch_id
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result) {
        if(result.status == 1) {
            var url = '#/selectcity/';
            var city = result.data.city_league;
            if(city != ''  && city.league_id != '') {
                var url = '#/selectcity/' + city.city_name +'/1';
            }
            city.city_name = base.replaceString(city.city_name,'市','');
            city.city_url = url;
            result.data.city_league = city;
            navigation.menu = result.data;
        } else {
            navigation.menu = null;
        }
        navigation.menuMode();
        // navigation.menuStatus = 1;
    }});
}

/**
 * 返回模导航
 * @method navigation.returnMode
 * @param {String} title 名称
 * @return {Null}
 */
navigation.returnMode = function(title) {
    html = template('header_top', {});
    $('#app-header-top').html(html);
    var name = '<i class="icon-chevron-left icon-large">';
    $('#nav-left').html(name);
    $('#nav-center').html(title);
    $('#nav-left').attr('onclick','history.back()');
    navigation.setHeaderHeight();
}

/**
 * 获得地区名字
 * @method navigation.getPartName
 * @return {String} String
 */
navigation.getPartName = function() {
    var city = select_area.city_list[user.userBase.city_code];
    var part = user.userBase.short_name;
    city = base.replaceString(city,'市','');
    return city + part;
}

/**
 * 获得导航的高设,让导航浮动在顶部
 * @method navigation.setHeaderHeight
 * @return {Null}
 */
navigation.setHeaderHeight = function() {
    if(!common.isNull(user.userBase.user_type) && user.userBase.user_type != 1 && _is_app != 1) {
        $('#header-focus').show();
    }
    $('#app-header').css('position','fixed');
    var height = $('#app-header').height();
    $('#view_page').css('paddingTop', parseInt(height) + 'px');
}
/**
 *  App信息推送管理
 */
var notice = {};
notice.page = 1; //加载页数
notice.news = 0; //消息数
notice.isOpen = 'open'; //窗口打开
notice.voucherNews = 0;//优惠券数
notice.returnStatus = 0; //控制返回状态
notice.loadData = 1; //允许数据加载
notice.loadCount = 0; //加载次数

/***
 * 信息列表
 * @method notice.list
 */
notice.list = function() {
    notice.page = 1;
    notice.loadCount = 1;

    common.renderTpl('#app_content','notice/notice_list',{});
    common.loaded(0);
    notice.addNewData();
    notice.control('list');
    notice.returnStatus = 1;

    if(user.userBase.none_letter_count > 0) {
        user.userBase.none_all_count = parseFloat(user.userBase.none_all_count) - parseFloat(user.userBase.none_letter_count);
        user.userBase.none_letter_count = 0;
    }

    if(config.appid != 1) {
        window.plugins.jPushPlugin.setApplicationIconBadgeNumber(0);
    }
}

/**
 * 信息提示控制
 * @method notice.control
 * @param {String} type 类弄
 */
notice.control = function(type) {
    switch (type) {
        case 'list': //消息列表
            app_cinfig.news = 0;
            $('#li-notice span').removeClass('icon-notice-active');
            $('#active-btn img').attr('src','ui/images/header/account.png?201603018');
            break;
        case 'menu'://头部菜单
            if(app_cinfig.news == 1) {
                $('#active-btn img').attr('src','ui/images/header/account_active.png?201603018');
            }
            break;
        case 'voucher': //优惠券
            app_cinfig.voucherNews = 0;
            $('#li-coupons span').removeClass('coupons-active');
            break;
        case 'sidebar': //侧边栏
            if(app_cinfig.news == 1) {
                $('#li-notice span').addClass('icon-notice-active');
            }
            if(app_cinfig.voucherNews == 1) {
                $('#li-coupons span').addClass('coupons-active');
            }
            break;
        case 'event':
            if(app_cinfig.voucherNews == 1) {
                $('#li-coupons span').addClass('coupons-active');
            }
            $('#li-notice span').addClass('icon-notice-active');
            $('#active-btn img').attr('src','ui/images/header/account_active.png?201603018');
            break;
    }
}

/**
 * 生成html
 * @method notice.createHtml
 * @param {Objcet} data
 */
notice.count = 0;
notice.createHtml = function(data) {
    var i = 0;
    var html = '';
    for(var item in data) {
        if(config.appid == 1 && data[item].push_type != 'letter' && data[item].push_type != 'appraise' ) {
            continue;
        }
        switch (data[item].push_type) {
            case 'Jpush_voucher_get': //领取代金券
                html += template('notice/notice_voucher_tpl', data[item]);
                break;
            case 'Jpush_voucher_timeout': //代金券过期提醒
                html += template('notice/notice_voucher_out_tpl', data[item]);
                break;
            case 'Jpush_naxin': //纳新计划推送消息
                html += template('notice/notice_privilege_tpl', data[item]);
                break;
            case 'Jpush_qunfa': //群发消息
                var tpl = '';
                switch (data[item].type) {
                    case 'news':
                        tpl = 'notice/notice_post_tpl';
                        break;
                    case 'text':
                        tpl = 'notice/notice_text_tpl';
                        break;
                }
                if(data[item].platform == 'all') {
                    html += template(tpl, data[item]);
                }
                if(config.appid == 2 && data[item].platform == 'ios' ) {
                    html += template(tpl, data[item]);
                }
                if(config.appid == 3 && data[item].platform == 'android' ) {
                    html += template(tpl, data[item]);
                }
                break;
            case 'Jpush_order_sending': //订单送货中
                html += template('notice/notice_order_sending_tpl', data[item]);
                break;
            case 'Jpush_order_complete': //订单完成
                data[item].uid = user.userBase.id;
                html += template('notice/notice_order_complate_tpl', data[item]);
                break;
            case 'Jpush_shelves_notice': //上价通知
                html += template('notice/notice_shelves_tpl', data[item]);
                break;
            case 'Jpush_downprice_notice': //降价通知
                html += template('notice/notice_downprice_tpl', data[item]);
                break;
            case 'letter': //站内信
                html += template('notice/notice_letter_tpl', data[item]);
                break;
            case 'appraise': //商品回复
                console.log('t');
                html += template('notice/notice_common_tpl', data[item]);
                break;
        }
        i++;
        if(i < 10) {
            notice.loadData = 0;
        }
    }

    if( html == '') {
        notice.count++;

    }
    $('#notice-list-inner').append(html);
}

/**
 * 加载新的数据
 * @method notice.addNewData
 */
notice.addNewData = function() {
    $('#notice-list').dropload({
        scrollArea : window,      //滑动区域，默认是绑定元素本身，但是不绑定window在iphone上会出错
        domDown : {      //下方DOM上拉时自定义父元素，会出现绑定的元素下面
            domClass   : 'dropload-down',      //整个自定DOM的样式
            domRefresh : '<div class="dropload-refresh">↓下拉加载更多</div>',     //上拉状态
            domLoad    : '<div class="dropload-load"><span class="loading"></span>加载中...</div>',      //正在加载中
            domNoData  : '<div class="dropload-noData">无更多数据了</div>'    //没有数据更新了
        },
        loadDownFn : function(me) {
            if(notice.count >= 3) {
                me.lock('down');
                notice.loadData = 0;
                $('.dropload-down').hide();
                common.renderTpl('#notice-list-inner','common/common_no_result',{tips:'没有消息哦～'});
                return false;
            }
            var url= api_host + "/Api/Jpush/get_push_list";
            //user.app_bingo_openid = '305b287c6205491ce61639610bad4ad6054681b9';
            //user.userBase.id = 0;
            //console.log(user.user_id);
            user.app_bingo_openid = user.app_bingo_openid || -1;
            var data = { openid: user.app_bingo_openid,user_id:user.userBase.id, page_next:notice.page, pages: 10 };
            $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result) {
                if(notice.loadCount == 1 && result.data == '' ) {
                    me.lock('down');
                    notice.loadData = 0;
                    $('.dropload-down').hide();
                    common.renderTpl('#notice-list-inner','common/common_no_result',{tips:'没有消息哦～'});
                    return false;
                 }

                if(result.status == 1) {
                    if(result.data != '') {
                        notice.createHtml(result.data);
                        notice.page++;
                        notice.loadCount++;
                    }
                } else {
                    tipsBox.createAlertBox(result.data);
                }

                if(notice.loadData == 1) {
                    setTimeout(function () {
                        me.resetload();
                    }, 2000);// 为了测试，延迟1秒加载，每次数据加载完，必须重置
                } else {
                    $('.dropload-down').hide();
                    me.lock('down');
                }

            }, error: function(xhr, type){
                tipsBox.createAlertBox("抱歉，数据加载失败，请重新尝试。如果情况依旧请联系我们客服。");
                me.resetload();// 即使加载出错，也得重置
            }});
        },
    });
}


/**
 * 信息详情
 * @method notice.post
 */
notice.post = function(id) {
    var url= api_host + "/Api/Jpush/get_push_content";
    var data = { id :id };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        if(result.status == 1) {
            common.renderTpl('#app_content','notice/notice_post',result.data);
            $('#notice-post-main').html(result.data.text);
            $('#notice-post-main img').css('width','100%');
            common.loaded(0);
        } else {
            tipsBox.createAlertBox(result.data);
        }
    }});
}
/**
 * Created by wang on 15/1/27..
 */

var order_list = {};
order_list.get_no_receive_data = '';
order_list.get_no_receive_status = '';
order_list.get_receive_data = '';
order_list.get_receive_status = '';
order_list.cancel_order_status = 0;
order_list.return_time = 0; //退货充许时间
order_list.map_model = 1; //0为加盟商地图模式，1为加盟商手动输入模式
order_list.tracking = {'1':'顺丰快递','2':'邮政快递'};

var order_address_modify = {}
/**
 * 显示订单列表
 * @method order_list.showOrderlist
 * @param {String} type 订单列表类型
 */
order_list.showOrderList = function(type) {
    order_list.get_no_receive_data = '';
    order_list.get_no_receive_status = '';
    order_list.get_receive_data = '';
    order_list.get_receive_status = '';

    var html = template('order/order',{});
    $("#app_content").html(html);

    common.loaded(0);
    order_list.menu(type);
}

/**
 * 订单菜单
 * @method order_list.menu
 * @param {String} type 订单类型
 */
order_list.menu = function(type){
    $('#header-common-main span').removeClass('ft-color');
    $('#header-common-main span').removeClass('bd-color');
    $('#'+type+'-btn').addClass('ft-color');
    $('#'+type+'-btn').addClass('bd-color');

    $("#order_tabs .active").hide();
    $("#order-"+type+"-list").show();
    $("#order_tabs .active").removeClass("active");
    $("#order-"+type+"-list").addClass("active");

    switch (type) {
        case 'noreceive':
            order_list.get_no_receive();
            break;
        default:
            order_list.get_receive();
            break;
    }
};

/**
 * 显示/隐藏菜单
 * @method order_list.showMenu
 * @param {Number} status 状态, 0,隐藏，1,显示
 */
order_list.showMenu = function(status) {
    var page = $('#page-mark').val();
    if(page == 'order') {
        if(status == 1) {
            $('#app-header').show();
        } else {
            $('#app-header').hide();
        }
    }
    return false;
}

/**
 * 获取未收货列表
 * @method order_list.get_no_receive
 * @returns {boolean}
 */
order_list.get_no_receive = function(){
    if(order_list.get_no_receive_status == 1) {
        var html = template('order/order_no_receive', order_list.get_no_receive_data.data);
        $("#order-noreceive-list").html(html);
        return true;
    }
    if(order_list.get_no_receive_status == 2) {
        common.noFoundResult('没有未收货订单','#order-noreceive-list');
        return true;
    }

    //加载loading
    $('.valuation-loading-mark').show();
    $('.valuation-loading-box').show();

    // $('#order-loading').show();
    var openid = user.userBase.bingo_openid;
    var url = api_host+"/Api/Order/order_list";
    var notReceive_data = { bingo_access_token: openid, bingo_openid: openid, status :'notReceive' };
    $.ajax({type:'post',url:url,data:notReceive_data,dataType: 'json',success:function(result){
        order_list.map_model = result.data.map_model;    //配置地址输入模式

        if(result.data.order != '') {
            order_list.get_no_receive_status = 1;
            order_list.get_no_receive_data = result;
            order_list.return_time = result.data.return_time;

            var html = template('order/order_no_receive', result.data);
            $("#order-noreceive-list").html(html);
        } else {
            order_list.get_no_receive_status = 2;
            common.noFoundResult('没有未收货订单','#order-noreceive-list');
        }
        // 关闭loading
        $('.valuation-loading-mark').hide();
        $('.valuation-loading-box').hide();
        // $('#order-loading').hide();
    }});
};


/**
 * 获取已收货订单
 * @method order_list.get_receive
 * @returns {boolean}
 */
order_list.get_receive = function(){
    if(order_list.get_receive_status == 1) {
        var html = template('order/order_receive', order_list.get_receive_data.data);
        $("#order-receive-list").html(html);
        return true;
    }
    if(order_list.get_receive_status == 2) {
        common.noFoundResult('没有已收货订单','#order-receive-list');
        return true;
    }
    $('#order-loading').show();
    var openid = user.userBase.bingo_openid;
    var url = api_host + "/Api/Order/order_list";
    var notReceive_data = { bingo_access_token: openid ,bingo_openid: openid ,status:'receive' };
    $.ajax({type:'post',url:url,data:notReceive_data,dataType: 'json',success:function(result){
        if (result.data.order.length > 0) {
            order_list.get_receive_status = 1;
            order_list.get_receive_data = result;
            order_list.return_time = result.data.return_time;
            for(var k in result.data.order) {
                result.data.order[k]['is_return_time_out'] = order_list.isReturnTimeOut(result.data.order[k]['delivery_time']);
            }
            var html = template('order/order_receive', result.data);
            $("#order-receive-list").html(html);
        } else {
            order_list.get_receive_status = 2;
            common.noFoundResult('没有已收货订单','#order-receive-list');
        }
        $('#order-loading').hide();
    }});
};

/**
 * 用户取消订单
 * @method order_list.cancelOrder
 * @param {Number} id 订单id
 * @param {Number} status 订单壮态
 * @param {String} tracking_number 第三方配送订单号
 * @returns {boolean}
 */
order_list.cancelOrder = function(id, status, tracking_number){
    if(tracking_number != '' &&  tracking_number != null) { //第三方配送,快递员取件后,不能取消订单
        tipsBox.createAlertBox('快递员已取单,不能取消订单');
        return false;
    }

    if(status == 1) {
        tipsBox.createAlertBox('快递员正在送货中,不能取消订单');
        return false;
    }
    $("#cancel-order-id").val(id);
    tipsBox.createConfirmBox('该订单将被取消,确定吗?', 'order_list.sureCancelOrder', id, '确定');

    //按钮点击统计
    common.buttonClikcStatistics("noreceive","noreceive_cancel","取消订单");
};

/**
 * 用户确定取消订单
 * @method order_list.sureCancelOrder
 * @param {Number} id 订单id
 * @returns {boolean}
 */
order_list.sureCancelOrder = function(id){
    if(order_list.cancel_order_status == 1) {
        tipsBox.createAlertBox('订单正在取消中,请稍候...');
        return false;
    }
    tipsBox.hideTipsBox();
    order_list.cancel_order_status = 1;

    var url = api_host+"/Api/Order/order_operate";
    var openid = user.userBase.bingo_openid;
    var data = { bingo_access_token: openid ,order_id: id, type:'cancel' };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        if (result.status == 1){
            order_list.get_no_receive_status = 0;
            order_list.get_no_receive();
        }else{
            tipsBox.createAlertBox(result.data);
        }
        order_list.cancel_order_status = 0;
    }});
};

order_list.userClickCancelOrder=function(){
    $("#cancel-order-id").val('');
    $(".cancel-user-order-wrap").hide();
};

order_list.get_delivery_area=function(){
    var url = api_host+"/Api/league/get_delivery_area";
    var openid = user.userBase.bingo_openid;
    var data = { bingo_access_token:openid ,bingo_openid:openid };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        result.addr1 = user.userBase.short_name;
    }});
};

order_list.showOrderModify = function(id, addr2, league, branch,tracking_number) { //显示要修改的订单
    if(tracking_number != '' &&  tracking_number != null) { //第三方配送,快递员取件后,不能修改订单信息
        tipsBox.createAlertBox('快递员已取单,不能修改订单信息');
        return false;
    }

    if(order_list.map_model == 1 && addr2 == ''){
        $("#modify-addr2-"+id).text("请选择");
    }
    $('.order-fixed-info').show();
    $('.order-fixed-sure').hide();
    $('.adress-box').hide();
    /*
     var url = api_host+"/Api/league/get_delivery_area";
     var openid = user.userBase.bingo_openid;
     var data = { bingo_access_token: openid ,bingo_openid:openid, league_id: league, branch_id:branch };

     $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
     var area = result.data;
     var areaStr = '';
     for(var item in area) {
     var  selected = (addr2 == area[item]['area_name']) ? 'selected="selected"': '';
     areaStr += '<option data-fee="'+area[item]['fee']+'" data-free="'+area[item]['fee_free']+'" value="'+area[item]['area_name']+'" '+selected+'>'+area[item]['area_name']+'</option>';
     }
     $('#select-part-'+id).html(areaStr);
     }});*/

    $('#order-fixed-sure-show-'+id).hide();
    $('#address-'+id).show();
    order_list.initModifyAddress(id);
    $('#order-fixed-sure-'+id).css('display','block');
    sco_height = parseInt($(window).height());
}

order_list.initModifyAddress = function(id) { //记录修改订单信息之前的数据
    var send_type = $('#modify-send_type-'+id).val();
    if(send_type == 1 || send_type == 3){
        order_address_modify.userName = $('#modify-realname-'+id).html();
        order_address_modify.userTel = $('#modify-tel-'+id).html();
    }else if(send_type == 2){         //自提
        order_address_modify.userName = $('#modify-realname-'+id).val();
        order_address_modify.userTel = $('#modify-tel-'+id).val();
    }
    order_address_modify.userAddr3 = $('#user_addr_'+id).html();
    order_address_modify.userRemark = $('#modify-remark-'+id).val();
}


order_list.userChangeAdress = function(id, total, delivery, pay_type, is_first_order) { //选择地区
    var selected = $("#select-part-"+id).val();
    var index = $("#select-part-"+id).get(0).selectedIndex;
    var fee = $("#select-part-"+id).children().eq(index).data('fee');
    var free = $("#select-part-"+id).children().eq(index).data('free');
    var realTotal = parseFloat(total) - parseFloat(delivery);
    // if(pay_type != 3) {
    //     if(is_first_order == 0 && realTotal < parseFloat(free)) {
    //          alertBox('.alert-box','由于您购买没满'+free+'元，本次购买需要收取'+fee+'元配送费');
    //     }
    // }
    $('#modify-addr2-'+id).html(selected);
}

order_list.modifyOrderIsChange = function(name,tel,addr2,addr3,remark) {
    if(order_address_modify.userName != name) {
        return 1;
    }
    if(order_address_modify.userTel != tel ) {
        return 1;
    }
    // if(order_list.map_model == 2){
    //     if(order_address_modify.userAddr2 != addr2 || addr2 == '请选择') {
    //         return 1;
    //     }
    // }

    if(order_address_modify.userAddr3 != addr3 ) {
        return 1;
    }
    if(order_address_modify.userRemark != remark ) {
        return 2;
    }
    return 0;
}

order_list.modifyOrderSubmit = function(id,pay_type) { //用户确定修改收货地址
    var send_type = $('#modify-send_type-'+id).val();
    if(send_type == 1 || send_type == 3){
        var realname = $('#modify-realname-'+id).text();
        var tel = $('#modify-tel-'+id).text();
    }else if(send_type == 2){         //自提
        var realname = $('#modify-realname-'+id).val();
        var tel = $('#modify-tel-'+id).val();
    }
    var addr1 = $('#user_area_'+id).html();
    var addr2 = '';
    var addr3 = $('#user_addr_'+id).html();

    var reciveTime = $('#modify-reciveTime-'+id).val();
    var remark = $('#modify-remark-'+id).val();
    var is_first_order = $('#modify-is_first_order-'+id).val();
    var status = order_list.modifyOrderIsChange(realname,tel,addr2,addr3,remark);
    if(status == 0) {
        $('#address-'+id).hide();
        $('#order-fixed-sure-'+id).hide();
        $('#order-fixed-sure-show-'+id).css('display','block');
        return false;
    }
    if(realname == '') {
        alertBox('.alert-box','请输入收件人名字');
        return false;
    }
    if(tel == '') {
        alertBox('.alert-box','请输入收货人的联系电话');
        return false;
    }

    // if(addr1 == '') {
    //     alertBox('.alert-box','请选择所在城市');
    //     return false;
    // }
    // if(order_list.map_model == 2){
    //     if(addr2 == '' || addr2 == '请选择') {
    //         alertBox('.alert-box','请选择地区');
    //         return false;
    //     }
    // }

    if(addr3 == '') {
        alertBox('.alert-box','请输入收件人详细地址');
        return false;
    }
    if(tel.length != 11 ) {
        alertBox('.alert-box','请输入11位手机号码');
        return false;
    }

    var reg = /^13[\d]{9}$|^14[0-9]\d{8}|^15[0-9]\d{8}$|^17[0-9]\d{8}|^18[0-9]\d{8}$/g;
    if(!reg.test(tel)) {
        alertBox('.alert-box','输入的手机号码有误');
        return false;
    }
    order_list.initModifyAddress(id);      //重新保存订单修改前的数据
    if($('#address_id-'+id).val() != 0){        //收货地址id不为空
        var address_id = $('#address_id-'+id).val();
    }else{
        var address_id = "";
    }
    var url=api_host+"/Api/Order/order_address_edit";
    var openid=user.userBase.bingo_openid;
    if (openid==undefined || openid==null || openid.length==0){
        return false;
    }
    var data={
        bingo_access_token:openid
        ,bingo_openid:openid
        ,order_id:id
        ,realname:realname
        ,tel:tel
        ,addr1:addr1
        ,addr2:addr2
        ,addr3:addr3
        ,send_type:send_type
        ,reciveTime:reciveTime
        ,remark:remark
        ,is_first_order:is_first_order
        ,address_id: address_id
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        if(result.status == 1) {
            if(status == 1) {
                alertBox('.alert-box','您已成功修改了收货地址信息');
            } else {
                alertBox('.alert-box','您已成功修改了备注信息');
            }
            $('#address-'+id).hide();
            $('#order-fixed-sure-'+id).hide();
            $('#order-fixed-sure-show-'+id).css('display','block');
            order_list.get_no_receive_status = 3;      //重新拿服务器数据
        } else {
            alertBox('.alert-box','抱歉，修改收货地址失败，请重新刷新页面或重新进入此页面');
        }
    }});
}

/**
 * 显示/隐藏订单支付方式
 * @method order_list.showPayMethod
 * @param {Number} status 状态: 0,隐藏, 1,显示
 * @param {Number} id 订单id
 * @param {String} orderno 订单号
 * @param {Number} payType 支付方式,只有参加了在线支付打折活动而且没支付才会有这个参数
 */
order_list.showPayMethod = function(status, id, orderno, payType) {
    if(status == 1) {
        var html = template('order/order_pay', {});
        $(tipsBox.container).html(html);
        $(tipsBox.container).show();
        $('#change_pay_type').data('id', id);
        $('#change_pay_type').data('orderno', orderno);
        tipsBox.tipsBoxCenter('.order-pay-wrap');
        if(_is_app == 1) { //App屏微信支付
            /*
            if(user.userBase.league_id == _headOffice) {
                $('#alipay-method').show();
            }*/
            $('#weixin-method').show();

        } else {
            $('#weixin-method').show();
            $('#alipay-method').hide();   //微信屏蔽支付宝
        }

        if(_groupPay.status == 1) { //团购临时屏了货到付款
            if($('#item-'+id+' div.order-item-main').data('isyugou') == 1) {
                var gid = $('#item-'+id+' table.order-item-tabel td').data('sub_id');
                if(_groupPay.gid == gid) {
                    $('#change_pay_type').hide();
                }
            }
        }

        //by feng/2016/06/12 解决在线支付打折支付不成功无法继续支付BUG，下单选择的是什么支付方式就显示什么支付方式
        // if(payType != undefined){
        //     //全部隐藏
        //     $('#orderPayInner li').each(function() {
        //         $(this).hide();
        //     });
        //     //显示取消按钮
        //     $('#cancel-methodBtn').show();
        //     if(payType == 1){   //微信支付
        //         $('#weixin-method').show();
        //     }else if(payType == 2){    //支付宝支付
        //         $('#alipay-method').show();
        //     }
        // }

    } else {
        tipsBox.hideTipsBox();
    }
}

/**
 * 用户修改订单收货方式
 * @method order_list.changePayMethod
 * @param {String} type 改变类型：changetype，本地支付，wxpay,微信支付，balance_type，余額支付
 * @returns {boolean}
 */
order_list.changePayMethod = function (type) {
    var id = $('#change_pay_type').data('id');
    var orderno = $('#change_pay_type').data('orderno');
    var url = api_host+"/Api/Order/order_operate";
    var openid = user.userBase.bingo_openid;
    var data = { bingo_access_token: openid ,order_id: id ,type: type };
    tipsBox.hideTipsBox();
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        if(result.status == 1) {
            switch(type) {
                case 'changetype': //货到付款
                    tipsBox.createAlertBox('您已成功修改了支付方式');
                    $('#go-to-play-'+id).hide();
                    $('#cancel-order-'+id).show();
                    break;
                case 'wxpay': //微信支付
                    switch (parseInt(_is_app)) {
                        case 0:
                            var host = window.location.host;
                            if (host  == "test.bingofresh.com"){//测试服务器
                                window.location.href='http://pay.bingofresh.com/wxpay_new/callpayjs.php?is_test=1&showwxpaytitle=1&order_id='+id;
                            } else if (host == "m.bingofresh.com" || host == "m2.bingofresh.com"){//正式服务器
                                window.location.href='http://pay.bingofresh.com/wxpay_new/callpayjs.php?showwxpaytitle=1&order_id='+id+'&open_id='+user.userBase.bingo_openid;
                            }
                            break;
                        case 1:
                            var host = window.location.host;
                            if (host  == "test.bingofresh.com"){//测试服务器
                                window.location.href='http://pay.bingofresh.com/wxpay_new/App_WxPay.php?is_test=1&order_id=' + id + '&platform=' + config.appid;
                            } else if (host == "m.bingofresh.com" || host == "m2.bingofresh.com"){//正式服务器
                                window.location.href='http://pay.bingofresh.com/wxpay_new/App_WxPay.php?order_id=' + id + '&platform=' + config.appid;
                            }

                            // cart.weixin_pay(id,orderno);
                            break;
                    }
                    break;
                case 'alipay': //支付宝支付
                    //window.location.href = 'http://pay.bingofresh.com/alipay/alipayapi.php?showwxpaytitle=1&order_id=' +id;
                    window.location.href = '#/aliPay/' +id+'/'+orderno;
                    break;
                case 'balance_type': //余额支付
                    window.location.href = '#/sure_play/' +id+'/'+orderno;
                    break;
            }
        } else {
            tipsBox.createAlertBox(result.data);
        }
    }});
}

/**
 * 退货是否超时了
 * @method  order_list.isReturnTimeOut
 * @param {Number} delivery_time 最晚退货时间
 * @returns {Boolen}
 */
order_list.isReturnTimeOut = function(delivery_time) {
    var timeOut = (parseInt(delivery_time) + parseFloat(order_list.return_time) * 60 * 60) * 1000;
    var timestamp = Date.parse(new Date());
    if(timestamp < timeOut ) {
        return 0;
    }
    return 1;
}

/**
 * 退货超时提示
 * @method order_list.isReturnTimeOutTips
 */
order_list.isReturnTimeOutTips = function() {
    tipsBox.createAlertBox('此订单已过了'+order_list.return_time+'小时，超过了退换货时间，如有疑问，请联系客服！');
}


/**
 * 缤果内部信息
 */
var news = {}

/**
 * 显示缤果内部信息
 * @method news.show_news
 * @param {Number} id 新闻：-3:使用帮用助，-2: 关于缤果
 */
news.show_news = function(id) {
    var url = api_host+"/Api/BaseService/get_news";
    var openid = user.userBase.bingo_openid;
    var data = { bingo_access_token: openid, id: id };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(data){
        common.renderTpl("#app_content", 'news', {});
        $("#news_content").html(data.data);
        $("#news_content img").css('width','100%');
        common.loaded(1);
        if(id == -2) {
            $('#header-common-main span').html('关于缤果');
        }
    }});
}

/*
 *缤果两周年生日活动    by：锋
 */
var birthday = {};
birthday.timerTaskt = null;
birthday.count = 0; //显示的次数
birthday.show_animation = function() {
    var url = api_host+"/Api/TempActivity/get_bingo_birthday_users";
    var openid = user.userBase.bingo_openid;
    var data = { bingo_access_token : openid ,bingo_openid: openid };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result) {
        if(result.status != 1) {
            home.show_product(0);
            return false;
        }
        birthday.count = 1;
        
        
        var i = 1;
        var host = window.location.host;
        if(host != 'test.bingofresh.com') {
            host = 'm.bingofresh.com';
        } 
        for (var k in result.data.user_list) {
            result.data.user_list[k]['index'] = i;
            result.data.user_list[k]['url'] = "http://"+host+"/user_upload/event/moneytree/"+result.data.user_list[k]['user_id']+".jpg?v="+result.data.nowtime;
            i++;
        }
        result.data.activeUrl = "http://"+host+"/actives-Birthday-index.html";
        var html = template('birthday_two',result.data);
        $("html,body").scrollTop(0);
        $("#app_content").html(html);

        var div_width = $('.font-zero').width();
        var li_margin = -(parseInt(div_width) + 6)/2;

        $('.font-zero').css('height',div_width+'px');
        $('.birthday_head_portrait_div li').css('margin',li_margin+'px 0 0 '+li_margin+'px');

        $('.transform-left').hide();
        $('#location-box').html('');
        $('#location-box').hide();
        home.show_my_cart_hide();        //清空购物车盒子
        ios_scroll_resert();           //优化IOS滚动

        $('.birthday_head_portrait').find('img').load(function(){
            $('#birthdaybg_loading').attr('src', 'ui/images/birthday/head_portrait.jpg?v=2015110601').load(function() {
               $('#birthdaybg_loading').remove();
               $('.loading-wrap').hide();
               $('.birthday').css('visibility','visible');
               birthday.timerTaskt = setTimeout("home.show_product(0)",8000);
            });
        });
    }});
}

birthday.go_product_list = function() { //弹出
    clearTimeout(birthday.timerTaskt);
    home.show_product(0);
}


/**
 * 双十一临昨banner
 */
var doubleEleven = {};
doubleEleven.tesk = null;
doubleEleven.jumpOut = function() { //跳过
    $('#doubleEleven').hide();
    clearTimeout(doubleEleven.tesk);
    _doubleEleven = 0;
}


doubleEleven.showBanner = function(status) { //显示banner
    if(parseInt(status) == 1) {
        $('#doubleEleven').show();
        doubleEleven.tesk = setTimeout("doubleEleven.jumpOut()",3000);
    }
}

/**
 * 纳新计划
 * create time: 2015/12/07
 * author: 亮
 */

var privilege = {}
privilege.show_privilege = function() {
    var host = window.location.host;

    if(host != 'test.bingofresh.com') {
        host = 'http://m.bingofresh.com';
    }  else {
        host = 'http://test.bingofresh.com';
    }
    var img = host + "/User-show_user_qr_img.html?uid=" + user.userBase.id + "&t=" + user.userBase.vip_code + "&avatar=" + user.userBase.avatar;
    //var img="http://test.bingofresh.com/User-show_user_qr_img.html?uid=1&t=gQEI8DoAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL25FT3hhVnJtRUo1cHRLeEhuRzNZAAIE2SFvVQMEgDoJAA==&avatar=http://wx.qlogo.cn/mmopen/6mqmdvt3dORiaZCTuDPoEYgT9fEfxuDcNevHxwbL8u8N26S0cQ1WGdw2mMzIQs5A2VvZWUWrnCO3e1ddxuCZZYzQt7DxTreua/0";
    //var data = { img: img, my_special_prize: _privilege.my_special_prize}
    var data = { img: img, my_special_prize: _privilege.my_special_prize+"?title="+_privilege_code[user.userBase.city_code].title}
    var html = template('privilege', data);
    $("#app_content").html(html);

    $('.private-voucher').html(_privilege_code[user.userBase.city_code].title);
    _code_title = '关注缤果得'+_privilege_code[user.userBase.city_code].money+'元代金券';

    common.loaded(1);
    $('#view_page').css('marginBottom','-50px');
    document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() {WeixinJSBridge.call('showOptionMenu');});
    share_info = {
        //"title":"缤果水果 - 全国领先水果电商",
        "title": _code_title,
        "img_url":"http://"+window.location.host+"/Public/Uploads/logo.jpg?v=2",
        "content":"",
        "url": _code_url + user.userBase.id
    };
}

privilege.show_privilege_opera = function(id,vip_code,avatar) {
    var host = window.location.host;
    if(host != 'test.bingofresh.com') {
        host = 'http://m.bingofresh.com';
    }  else {
        host = 'http://test.bingofresh.com';
    }
    var img = host + "/User-show_user_qr_img.html?uid=" + id + "&t=" + vip_code + "&avatar=" + avatar;
    var data = { img: img, my_special_prize: _privilege.my_special_prize+"?title=5元无限制代金券"};
    var html = template('privilege', data);
    $("#app_content").html(html);

    $('.private-voucher').html('5元无限制代金券');

    common.loaded(1);
    share_info = {
        "title": _code_title,
        "img_url": "http://"+window.location.host+"/Public/Uploads/logo.jpg?v=2",
        "content": _code_content,
        "url": _code_url + id
    };
}

privilege.show_privilege_info = function() {

    var data = {host: window.location.host}
    var html = template('privilege_info', {});
    $("#app_content").html(html);
    common.loaded(1);
    document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() {WeixinJSBridge.call('hideOptionMenu');});

}
privilege.showKnow = function() {
    var status = $('#privilege-know-show').val();
    if(status == 0) {
        $('.privilege-know h1 img').attr('src','./ui/images/share-up.png');
        $('.privilege-know ul').show();
        $('#privilege-know-show').val(1);
    } else {
        $('.privilege-know h1 img').attr('src','./ui/images/share-down.png');
        $('.privilege-know ul').hide();
        $('#privilege-know-show').val(0);
    }
}

/**
 * 查看纳新计划规则
 * @param {int} status 1:扩开,0:合上
 */
privilege.packUpBtn = function(status) {
    if(status == 1) {
        $('.privilege-rule-wrap').show();
        $('.privilege-footer').removeAttr('style');
        $('.privilege-footer').css('paddingBottom','0');
        $('.privilege-rule-btn').attr('onclick','privilege.packUpBtn(0)');
        $('.privilege-rule-btn img').attr('src','ui/images/privilege/one/pack-up-01.png');
    } else {
        $('.privilege-rule-wrap').hide();
        $('.privilege-footer').removeAttr('style');
        $('.privilege-footer').css('paddingBottom','10%');
        $('.privilege-rule-btn').attr('onclick','privilege.packUpBtn(1)');
        $('.privilege-rule-btn img').attr('src','ui/images/privilege/one/pack-up-02.png');
    }
}

/**
 * 显示分享
 * @param status
 */
privilege.shareBtn = function(status) {
    if(status == 1) {
        $('.privilege-mask').show();
    } else {
        $('.privilege-mask').hide();
    }
}


/**
 * 2015双12返利纳新入口
 * @param {string} mark_id
 */
privilege.enter = function(mark_id) {
    var host = window.location.host;
    if (host == 'test.bingofresh.com') {
        host = 'http://test.bingofresh.com';
    } else {
        host = 'http://boss.bingofresh.com';
    }

    var openid = user.userBase.bingo_openid;
    var url = host + "/admin.php?s=Complete/person_code";
    var data = { openid : openid, mark_id: mark_id };
    $.ajax({type:'post',url:url,data:data,dataType:'json',success:function(result){
        console.log(result);
        if(result.status == 1) {
            window.location.href = '#/privilege';
        } else {
            tipsBox.createAlertBox(result.data);
        }
    }});
}
/**
 * 产品的extend扩展功能
 */
var product_extend = {};
product_extend.voucher_data = { sum: 0, count: 0 };
product_extend.user_get_product_voucher_status = 1;
product_extend.firstComeTaskt = null; //用户首次进入定时器

/**
 * 设置产品页面的代金券
 * @param {object} data
 */
product_extend.set_product_voucher = function(data) {
    if(data == '' || data == 0) {
        return false;
    }

    if(common.isOwnEmpty(data)) {
        return false;
    }

    if(data.voucher_num == 0) {
        return false;
    }

    var num = 0;
    var count = 0;
    var voucher_list = data.voucherlist;
    var list = [];

    for(var item in voucher_list ) {
        if(voucher_list[item].class_mark == home.cur_product_class) {
            if (voucher_list[item].is_get != 0) {
                count++;
            }
            if (voucher_list[item].money > parseInt(voucher_list[item].money)) {
                var money = new Number(voucher_list[item].money);
                voucher_list[item].money = money.toFixed(2);
            } else {
                voucher_list[item].money = parseInt(voucher_list[item].money);
            }
            list.push(voucher_list[item]);
            num++;
        }
    }

    product_extend.voucher_data.count = count;
    product_extend.voucher_data.sum = num;
    if(num == count) {
        //return false;
    }
    data.voucher_list = list;

    if(common.isOwnEmpty(list)) {
        return false;
    }

    var html = template('product_voucher', data);
    $('#product-voucher').html(html);

    var width = $('.product-voucher-inner').width();
    if(num >= 2) {

        $('.product-voucher-main p').css('lineHeight','1.2');
        $('.product-voucher-main p.product-voucher-title').css('height','15px');
        $('.product-voucher-main p span').css('fontSize','1.5em');
        $('.product-voucher-main p.product-voucher-title').css('fontSize','0.875em');
        $('.product-voucher-item').css('width',parseInt(width / 2  * 0.95)+"px");
        $('.product-vocher-footer em').hide();
        $('.product-vocher-footer span').addClass('center');
        $('.product-voucher-inner table tr td:last-child div.product-voucher-item').css('float','right');
        $('.product-voucher-inner table tr td:last-child div.product-voucher-item').addClass('green');
    }
    if(num == 1) {
        $('.product-voucher-item').css('width',parseInt(width - 4)+"px");
    }
}

/**
 * 用户领取优惠券
 * @param {int} voucher_id
 */
product_extend.user_get_product_voucher = function(voucher_id,title) {
    if(product_extend.user_get_product_voucher_status != 1) {
        return false;
    }

    var status = $('#product-voucher-item-0'+voucher_id).data('status');
    if(status != 0) {
        product_extend.get_voucher_tips(voucher_id,status);
        return;
    }

    product_extend.user_get_product_voucher_status = 0;
    var openid = user.userBase.bingo_openid;
    var url= api_host + "/Api/Voucher/get_give_voucher";
    var data = { bingo_access_token: openid, bingo_openid: openid, voucher_id: voucher_id, class_name: home.cur_product_class, app_id: config.appid  };
    $.ajax({type:'post',url:url,data:data,dataType:'json',success:function(result){
        if (result.status == 1) {
            for(var i in home.productList.give_voucher_info) {
                if(home.productList.give_voucher_info[i].id == voucher_id) {
                    home.productList.give_voucher_info[i].is_get = 1;
                }
            }

            product_extend.hide_product_voucher();
            if(result.data != 1) {
                $('#product-voucher-item-0' + voucher_id).addClass('gray');
            }
            product_extend.get_voucher_tips(voucher_id, result.data);
            product_extend.vouchJpush(voucher_id,title);
        } else {
            tipsBox.createAlertBox(result.data);
        }
        product_extend.user_get_product_voucher_status = 1;
    }});
}

/**
 * 用户領取优惠券极光推送
 * @method product_extend.vouchJpush
 * @param {Number} id 优惠券id
 * @param {String} title 优惠券名称
 */
product_extend.vouchJpush = function(id, title) {
    if(_is_app != 1) {
        return false;
    }
    var url = api_host + '/Api/Jpush/single_push';
    //user.app_bingo_openid = '305b287c6205491ce61639610bad4ad6054681b9';
    //config.appid = 2;
    var txt = '恭喜你，在领取代金券活动中，你获得'+title;
    var data  = { bingo_openid: user.app_bingo_openid, push_type: 'Jpush_voucher_get', platform: config.appid, push_value: id, txt: txt };
    $.ajax({type:'post',url:url,data:data,dataType:'json',success:function(result){}});
}

/**
 * 隐藏产品的优惠券
 * @return {void}
 */
product_extend.hide_product_voucher = function() {
    product_extend.voucher_data.count++;
    if(product_extend.voucher_data.count == product_extend.voucher_data.sum) {
        //$('#product-voucher').hide();
    }
}

/**
 * 领取优惠券提示
 * @method product_extend.get_voucher_tips
 * @param {Number} id
 * @param {Number} status
 */
product_extend.get_voucher_tips = function(id, status) {
    var tips = '';
    switch (parseInt(status)) {
        case -49:
            tips = '你来晚了，该优惠券已经领取完了';
            break;
        case -48:
            status = -49;
            tips = '恭喜你成功领取本券！购买商品时记得使用哟!';
            break;
        case -59:
            tips = '你已经领取过了,不能再领了';
            break;
        case -58:
            status = -59;
            tips = '恭喜你成功领取本券！购买商品时记得使用哟!';
            break;
        case 1:
            status = 0;
            tips = '恭喜你成功领取本券！购买商品时记得使用哟!';
            break;
        default :
            tips = '优惠券发放失败';
            break;
    }
    for( var item in home.productData.data.give_voucher_info.voucherlist ) {
        if(home.productData.data.give_voucher_info.voucherlist[item].id == id) {
            home.productData.data.give_voucher_info.voucherlist[item].is_get = status;
        }
    }
    $('#product-voucher-item-0'+id).data('status', status );
    tipsBox.createAlertBox(tips);
}

/**
 * 用户首次进来
 * @method product_extend.firstCome
 */
product_extend.firstCome = function() {
    //common.delCookie('first_come');
    //common.delCookie('user_first_come');
    //return false;
    var first_come = common.getCookie('user_first_come');
    if(first_come == 1) { //不再提示
        return false;
    }
    $('#user-first').show();
    common.setCookie('user_first_come',1,365);
    //product_extend.firstComeTaskt = setTimeout("product_extend.firstComeHide()",6000);


}
var friend_come_is_show=0;
product_extend.friendCome = function() {
    if (friend_come_is_show==1 || user.userBase==undefined){
        return false;
    }

    //console.log(user.userBase);
    //宾哥老友显示
    if (parseInt(user.userBase.level_id)>0  && user.userBase.memeber_time_out == "0" && (user.userBase.city_code == "0760" || user.userBase.city_code == "0756")){
        var friend_come = common.getCookie('friend_first_come');
        if(friend_come == 2) { //不再提示
            return false;
        }
        friend_come_is_show=1;
        //console.log("show");
        $('#user-first').hide();
        $('#friend-first').show();
        return false;
    }
}

var new_version_come_is_show=0;
product_extend.newVersionCome = function() {
    if (new_version_come_is_show==1 || user.userBase==undefined){
        return false;
    }

    if (box_model == 1 && (user.userBase.league_id == '10' || user.userBase.league_type == 'hezi') && user.userBase.branch_id == "" && user.userBase.area_name != "沙溪"){
        var friend_come = common.getCookie('new_version_come');
        var friend_come2 = common.getCookie('new_version_come2');
        if(friend_come == 2){
            //如果存在旧的版本提示，就删除该cookie
            common.delCookie('new_version_come');
        }
        if(friend_come2 == 2) { //不再提示
            return false;
        }
        friend_come_is_show = 1;    //如果显示了新版本提示，就不显示会员提示
        new_version_come_is_show = 1;
        //console.log("show");
        $('#user-first').hide();
        $('#newVersionFirst').show();
        return false;
    }
}

/**
 * 隐藏新版本提示
 * @param {Number} type
 * @return {Boolean}
 */
product_extend.newVersionFirstHide = function(type){
    $('#user-first').hide();
    $('#newVersionFirst').hide();
    ///clearTimeout(product_extend.firstComeTaskt);
    if(type == 1){
        common.setCookie('new_version_come2',2,1);
    }
    if (type == 2){
        common.setCookie('new_version_come2',2,365);
    }
    return true;
}

/**
 * 隐藏首次进入
 * @return {void}
 */
product_extend.firstComeHide = function() {
    $('#user-first').hide();
    ///clearTimeout(product_extend.firstComeTaskt);
    return true;
}


/**
 * 隐藏老友首次进入
 * @return {void}
 */
product_extend.friendComeHide = function(type) {
    $('#user-first').hide();
    $('#friend-first').hide();
    ///clearTimeout(product_extend.firstComeTaskt);
    if (type==2){
        common.setCookie('friend_first_come',2,365);
    }
    return true;
}

/**
 * 引导用户关注
 * @return {void}
 */
product_extend.user_focus = function() {
    if(!common.isNull(user.userBase.user_type) && user.userBase.user_type != 1 && _is_app != 1) {
        var height = 0;
        $('#header-focus').show();
        height = $('#header-focus').height();
        $('#header-focus').addClass('header-focus-position');
        $('.product-info-header').css('marginTop',height);
        $('#return-btn').css('top',height + 15);
    }
}
/**
 * Created by wang on 15/2/2.
 */

var product_package={};
product_package.show=function(){
    var url=api_host+"/Api/Product/product_package_list";
    var openid=user.userBase.bingo_openid;
    if (openid==undefined || openid==null || openid.length==0){
        return false;
    }
    var data={
        bingo_access_token:openid
        ,bingo_openid:openid
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        var list=result.data;
        for (var i=0;i<list.product.length;i++){
            list.product[i]["num"]=1;
            product_package_list[list.product[i]["id"]]=list.product[i];
        }
        var html = template('product_package', list);
        $("#app_content").html(html);
        $("#home_nav .current").removeClass('current');
        $("#li_product_package").addClass('current');
        render_user();
        minHeight();
    }});
};
product_package.view=function(id,type){
    var url=api_host+"/Api/Product/product_view";
    var openid=user.userBase.bingo_openid;
    if (openid==undefined || openid==null || openid.length==0){
        return false;
    }
    var data={
        bingo_access_token:openid
        ,id:id
        ,type:"package"
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        var list=result.data;
        var html = template('package_view', list);
        $("#app_content").html(html);
        $("#package_conten").html(list.content);
        if (type=="normal"){
            $("#cart-btn").attr('href',"javascript:void(0);");
            $("#cart_price").attr('onclick',"product_package.buy(0,"+list.id+","+list.price+"),0");
            $("#cart_price").text('我要购买礼盒');
        }
        render_user();
    }});
};
//购买
product_package.buy=function(id,pid,price,online_pay){
    //console.log(product_package_list[pid],price);
    if (product_package_list[pid]==undefined){
        alert("出错了，请返回重试");
        return false;
    }
    var p=pid+","+product_package_list[pid]["title"]+',1,'+price;
    product_package_list[pid]["price"]=price;
    cart.data.package_info.id=pid;
    cart.data.package_info.pre_id=id;
    cart.data.online_pay=online_pay;
    setCookie('buycar',p);
    //console.log(getCookie('buycar'));
    window.location.href="#/cart/3";
}

/**
 * Created by wang on 15/2/2.
 */
var product_special={is_begin:0};
//显示列表
product_special.online_num = 0;
product_special.special_car_info = '';
product_special.teming_car = ''; //定时购物车
product_special.teming_car_tips = ''; //定时购物车提示
product_special.close_tips_box_plan = '';
product_special.teming_car_start_tips = 0;

product_special.add_btn_status = 0;
product_special.minus_btn_status = 0;
product_special.repeat_clear_opreta = '';
product_special.join_special_car = {};
product_special.special_fruit_img = {};
product_special.special_over_time = new Array();
product_special.daojishi_over_status = 1; //倒计时已结束
product_special.banner = {};
product_special.headOffice = 0;
product_special.headOfficeLeagueId = 99999; //总部发起抢购lid标识符

product_special.init = function(id) {
    config.cart_init();
    var data = home.get_product_param();
    $.ajax({type:'post',url:data.url,data:data.param,dataType: 'json',success:function(result){
        home.set_group_data(result.data.groupbuy);
        home.set_small_group_data(result.data.small_group);
        product_special.banner = home.getCurrentClassBanner(result.data.banner.top,'promotion');
        product_special.show_v2(id);
    }});
}

/**
 * 获得所有分类
 * @method product_special.getAllClass
 * @method {Number} id
 */
product_special.getAllClass = function(id) {
    var branch_id = "";
    if(user.userBase.branch_id !== "") {
        branch_id = user.userBase.branch_id;
    }
    var url = api_host + "/Api/Product/league_nav";
    var openid = user.userBase.bingo_openid;
    var data = {
        bingo_access_token: openid
        ,bingo_openid: openid
        ,league_id: user.userBase.league_id
        ,branch_id: branch_id
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result) {
        if(result.status == 1) {
            if(result.data.nav != '') {
                home.allClass = result.data.nav;
            }
        }
        product_special.show_v2(id);
    }});
}

product_special.show_v2 = function(id) {
    navigation.menuType = 0;
    if(home.groupStatus == 0) {
        product_special.init(id);
        return false;
    }

    var url=api_host+"/Api/Product/special_list2";
    var openid=user.userBase.bingo_openid;
    product_special.daojishi_over_status = 1;
    if (openid==undefined || openid==null || openid.length==0){
        return false;
    }
    var data={
        bingo_access_token:openid
        ,bingo_openid:openid
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        var active_id = 0;
        var next_active_current = 0;
        result.data.now_active_status = 0;
        result.data.next_active_status = 0;
        result.data.active_is_ready = 0;
        result.data.now_active_info = '';
        result.data.next_active_info = '';
        result.data.special_list = '';
        result.data.online_num = product_special.online_num;
        result.data.join_special_car = product_special.join_special_car;

        for (var k in result.data.hd_list) {
            result.data.hd_list[k].index = k;
            result.data.hd_list[k].next_active_current = 0;
            if((result.data.hd_list[k].is_cur == 1 || result.data.hd_list[k].is_cur == -1) && result.data.special_list == '') {
                active_id = result.data.hd_list[k].id;
                result.data.special_list = result.data.hd_list[k].special_list;

                if(result.data.active_not_over == 0 && result.data.hd_list[k].is_cur == -1 ) {
                    result.data.active_not_over = 1;
                }
                if(result.data.hd_list[k].is_cur != 1) {
                    product_special.daojishi_over_status = 0;
                }

            }
            if(result.data.hd_list[k].is_cur == 1) {
                result.data.now_active_status = 1;
                if(result.data.now_active_info == '') {
                    result.data.now_active_info = {active_id:result.data.hd_list[k].id, active_name:result.data.hd_list[k].title,start_time:result.data.hd_list[k].st};
                }
            }
            if(result.data.hd_list[k].is_cur == -1) {
                result.data.next_active_status = 1;
                if(result.data.next_active_info == '') {
                    result.data.next_active_info = {id:k,active_id:result.data.hd_list[k].id,active_name:result.data.hd_list[k].title,start_time:result.data.hd_list[k].st};
                }
                if(next_active_current == 0 && result.data.now_active_status == 0) {
                    next_active_current = 1;
                    result.data.hd_list[k].next_active_current = 1;
                }
            }
            if(result.data.hd_list[k].is_cur == 0) { //生成已超时水果数据
                product_special.special_over_time[k] = result.data.hd_list[k];
            }
        }
        result.data.img_v = _img_v;
        result.data.next_active_status = (result.data.now_active_status == 1) ? 0 : result.data.next_active_status; //特价是否有下一场
        result.data.special_status = (result.data.now_active_status || result.data.next_active_status )  ? 1 : 0; //特价水果是否结束了
        result.data.active_is_ready = (result.data.special_list != '')  ? 1 : 0; //特价水果是否准备好水果

        var html = template('product_special_v2', result.data);
        if(!id) {
            $("#app_content").html(html);
        }

        $("#home_nav .current").removeClass('current');
        $("#li_product_special").addClass('current');

        if(result.data.next_active_status == 1) { //显示预购倒计时
            product_special.daojishi(result.data.next_active_info.start_time,result.data.time);
        }

        var products=[];
        if(result.data.special_list != '') { //特价水果列表
            for (var k in result.data.special_list){
                result.data.special_list[k]['num'] = 1;
                product_special_list[result.data.special_list[k]["id"]] = result.data.special_list[k];
                product_special_list[result.data.special_list[k]["id"]]['active_id'] = active_id;
                products.push(result.data.special_list[k]["id"]);
                if(id == result.data.special_list[k]['id']) {
                    home.show_product_info(result.data.special_list[k]["id"],'special');
                    return false;
                }
            }
        }

        if((!common.isOwnEmpty(product_group_list) || !common.isOwnEmpty(product_small_group_list)) && _is_app != 1 ) {
            var html = template('product_group', { group_list: product_group_list, small_group_list: product_small_group_list });
            $('#group_list').html(html);

            if(!common.isOwnEmpty(product_group_list)) {
                $('#group-line').show();
            }
            if(!common.isOwnEmpty(product_small_group_list)) {
                $('#small-group-line').show();
            }
        }

        home.setBanner(product_special.banner);

        if(id) {
            window.location.href = '#/home';
            return false;
        }
        home.cur_product_class = 'product_special';
        product_special.getNewKucun();

        special_queue.emit('join room',{league_id:user.userBase.league_id,user_id:user.userBase.id,products:products});
        special_queue.emit('join room',{league_id:product_special.headOfficeLeagueId,user_id:user.userBase.id,products:products});
        search.changeSearchModel(0);
        config.lazyLoadImage();
        common.loaded(1);
    }});
};

/**
 * 获得特价团购数据
 * @method product_special.getSpecialGroupData
 */
product_special.getSpecialGroupData = function() {
    if(common.isOwnEmpty(home.allClass)) {
        return;
    }
    var class_mark = '';
    var group_list = [];
    var data = product_group_list;

    for(var i in data) {
        data[i].is_special_group = 1;
    }
    for(var i in home.allClass) {
        class_mark = home.allClass[i].class_mark;
        for(var j in data) {
            if(data[j].class_mark == class_mark) {
                data[j].is_special_group = 0;
            }
        }
    }
    for(var i in data) {
        if(data[i].is_special_group == 1) {
            group_list.push(data[i]);
        }
        group_list.push(data[i]);
    }
    return group_list
}

product_special.getNewKucun = function() {
    var products=[];
    var headOffice = 0;
    var lid = user.userBase.league_id;
    var timestamp = Date.parse(new Date());
    for ( var k in product_special_list) {
        if(product_special_list[k].is_public == 1) {
            if(headOffice == 0) {
                lid = product_special.headOfficeLeagueId;
                headOffice = 1;
            }
            products.push(product_special_list[k]['pid']);
        } else {
            products.push(product_special_list[k]['id']);
        }
    }

    var pids = products.join(",");
    var aid = $('#active_id').val();
    var data={lid:lid,aid: aid,uid:user.userBase.id,pids:pids,timestamp:timestamp};
    $.ajax({type:'get', url:_node_host3+"/getNewKucun", data:data, dataType:'json',   success:function(result){
        if(result.status > 0 ) {
            for(var k in result.data) {
                if(result.data[k]['id'] != undefined) {

                    //var product = product_special_list[result.data[k]['id']];
                    var product = product_special.getHeadData(result.data[k]['id'],headOffice);

                    var id = product['id'];
                    var title = product['title'];
                    var price = product['price'];
                    var kucan = result.data[k]['num'];
                    var pid = 0;
                    if(headOffice == 1) {
                        pid = result.data[k]['id'];
                    }



                    $('.special_fruit_kucun_'+id).html(kucan);
                    if(kucan <= 0 && result.data[k]['is'] == 0  && product_special.daojishi_over_status == 1 ) {
                        var btn_str = '<a href="javascript:void(0);" class="sale_out_btn" onclick="tipsBox.createAlertBox(\'抢光了\');">抢光了</a>';
                        $('#special_fruit_btn_' + id).html(btn_str);
                    }
                    if (result.data[k]['is'] == 1 ) {
                        product_special.special_car(id, title, 1, parseFloat(price));
                        var btn_str = '<a href="javascript:void(0);" class="minus_btn" onclick="product_special.minus_btn(\'' + id + '\',\'' + title + '\',\'' + price + '\',\'' + pid + '\')">已抢</a>';
                        $('#special_fruit_btn_' + id).html(btn_str);
                        common.tongji();
                    }
                }
            }
        } else {
            tipsBox.createAlertBox(result.data);
        }
    }});
}

product_special.getHeadData = function(id,type) {
    if(type == 0) {
        return product_special_list[id];
    }
    for(var i in product_special_list) {
        if(product_special_list[i].pid == id) {
            return product_special_list[i];
        }
    }
}


product_special.products = function() {
    var products=[];
    for (var k in product_special_list){
        products.push(product_special_list[k]["id"]);
    }
    return products;
}

product_special.select_over_time_active = function(index,status){ //查看超时特价活动
    if($('#special_menu_0'+index+" p.special-type").html() != '未开启') {
        $('.special-performance-box ul li').removeClass('current');
        $('#special_menu_0'+index).addClass('current');
    }
    if(status == 0) {
        var html = template('special_over_time', product_special.special_over_time[index]);
        $('#special_over_time').html(html);
        $('.over_time_num_people').html( $('#online_people_num').val());
        $('.special-performance-box ul li').removeAttr('style');
        $('#special_now_active').hide();

    } else {
        $('#special_over_time').html('');
        $('.special-performance-box ul li').removeAttr('style');
        $('#special_now_active').show();
    }
    config.lazyLoadImage();
}

//购买
product_special.buy=function(id,title,price){
    if (product_special.is_begin==0){
        alert("马上开始了，请不要走开");
        return false;
    }
    var p=id+","+title+',1,'+price;
    setCookie('buycar',p);
    window.location.href="#/cart/1";
};


product_special.add_btn = function(id,title,price,pid,event){ //抢购水果加操作
    if(product_special.daojishi_over_status == 0) {
        tipsBox.createAlertBox('马上就开始了,请不要走开哦~');
        return false;
    }

    if(user.is_new_user == 0 && product_special_list[id]['for_new_user'] == 1) {
        tipsBox.createAlertBox(product_special_list[id]['title']+'是新用户专享哦~');
        return false;
    }

    var lid = product_special_list[id]['is_public'] == 1 ? product_special.headOfficeLeagueId : user.userBase.league_id;
    var aid = $('#active_id').val();

    var qiang_pid=id;
    if (product_special_list[id]['is_public']==1){
        qiang_pid = pid;
        product_special.headOffice = 1;
    }
    var timestamp = Date.parse(new Date());
    var data={lid: lid, aid: aid, uid: user.userBase.id, pid: qiang_pid, timestamp: timestamp};
    $.ajax({type:'get', url:_node_host3+"/qiang", data:data, dataType:'json', success:function(result){
        if(result.status == 1) {
            var imgSrc = $('#freeImg-' + id).attr('src');
            animateCart(imgSrc, event);
            product_special.special_car(id, title, 1, parseFloat(price));
            var btn_str = '<a href="javascript:void(0);" class="minus_btn" onclick="product_special.minus_btn(\'' + id + '\',\'' + title + '\',\'' + price + '\',\'' + pid + '\')">已抢</a>';
            $('#special_fruit_btn_' + id).html(btn_str);
            product_special.join_special_car[id] = 1;
            product_special.frist_buy();
            common.tongji();
        } else {
            tipsBox.createAlertBox(result.data);

        }
    }});
}

product_special.frist_buy = function() {
    if(product_special.teming_car_start_tips == 0) {
        product_special.teming_car_start_tips = 1;
        product_special.close_tips_box(1);
    }
}

product_special.minus_btn = function(id,title,price,pid) { //抢购水果减操作
    var tips = title+'已经给你抢到了，确定删除？';
    var param = id+','+title+','+price+','+pid;
    tipsBox.createConfirmBox(tips, 'product_special.sure_minus_btn',param, '删除');
}

product_special.sure_minus_btn = function(id,title,price,pid) { //确认抢购水果减操作
    var aid = $('#active_id').val();
    var timestamp = Date.parse(new Date());
    var qiang_pid = id;
    var lid = user.userBase.league_id;
    if (product_special_list[id]['is_public']==1){
        qiang_pid = pid;
        lid = product_special.headOfficeLeagueId;
    }
    var data={lid:lid,aid: aid,uid:user.userBase.id,pid:qiang_pid,timestamp:timestamp};
    $.ajax({type:'get', url:_node_host3+"/quxiao", data:data, dataType:'json', success:function(result){
        if(result.status == 1) {
            delete product_special.join_special_car[id];
            var kucan = $('.special_fruit_kucun_'+id).html();
            kucan = kucan || $('.special_fruit_kucun_'+pid).html();

            product_special.special_car(id,title,0,price);
            product_special.recover_special_btn(id,title,price,kucan);
            tipsBox.hideTipsBox();
            common.tongji();
            if($('#shop-cart-box').html() != ""){    //购物车操作
                $("#iteminfo-"+id).remove();      //移除该商品
                if($("#cart_num").html() == 0){     //当没有产品时关闭清空用户购物车
                    home.my_cart_hide();
                }
            }
        } else {
            tipsBox.createAlertBox(result.data);
        }
    }});
}

product_special.del_btn = function(id) { //抢购水果删除操作
    var timestamp = Date.parse(new Date());
    var aid = product_special_list[id]['active_id'];

    var data={lid:user.userBase.league_id,aid: aid,uid:user.userBase.id,pid:id,timestamp:timestamp};
    $.ajax({type:'get', url:_node_host3+"/quxiao", data:data, dataType:'json', success:function(result){
        delete product_special.join_special_car[id];
        product_special.special_car(id,product_special_list[id].title,0,product_special_list[id].price);

        var special_car = getCookie('special_car');
        if(special_car == null || special_car == '') {
            product_special.clear_user_special_car_data();
        }

        cart.count_show(0,0,"del");
        $("#special-fruit-"+id).remove();
        tipsBox.hideTipsBox();
        if (cart.data.all_num <= 0){
            window.location.href="#/home";
        }
    }});
}

product_special.plan_time_operate = function() { //定时操作数据
    if(product_special.teming_car == '') {
        if(product_special.teming_car_start_tips == 0) {
            product_special.teming_car_start_tips = 1;
            product_special.close_tips_box(1);
        }
        product_special.teming_car_tips = setTimeout("product_special.clear_teming_car_tips()",1000 * 60 * 8);
        product_special.teming_car = setTimeout("product_special.plan_time_trigger()",1000 * 60 * 10);
    }
}

product_special.close_tips_box = function(status) { //5之后秒关闭提示
    if(status == 1) {
        $('#special_over_time_tips').show();
        product_special.close_tips_box_plan = setTimeout("product_special.close_tips_box(0)",1000 * 6);
        $('#special_over_time_tips p').html('闪购商品要在10分钟完成结算哦，超过时间，你的闪购商品会被别人抢走哦～');
    } else {
        $('#special_over_time_tips').hide();
        clearTimeout(product_special.close_tips_box_plan);
    }
}

product_special.plan_time_trigger = function() { //定时操作触发
    if(product_special.add_btn_status != 0 || product_special.minus_btn_status != 0 ) {
        clearTimeout(product_special.teming_car);
        clearTimeout(product_special.repeat_clear_opreta);
        product_special.repeat_clear_opreta = setTimeout("product_special.plan_time_trigger()",10);
        return false;
    }

    product_special.execute_clear_operate();
    product_special.createConfirmBox();
}

product_special.execute_clear_operate = function() { //执行清空数据
    clearTimeout(product_special.repeat_clear_opreta);
    var special_car = getCookie('special_car');
    if(special_car == null) {
        product_special.clear_user_special_car_data();
        return false;
    }
    product_special.add_btn_status = 1;
    product_special.minus_btn_status = 1;
    // special_socket.emit('timing tast trigger');
    product_special.clear_user_special_car_data();
}

product_special.clear_teming_car_tips = function() { //关闭特价8分钟提示
    tipsBox.createAlertBox('闪购商品要在10分钟完成结算哦，你还有2分钟时间，超过时间，你的闪购会被别人抢走哦～');
    clearTimeout(product_special.teming_car_tips);
}

product_special.clear_user_special_car_data = function() { //清空用户特价购物车数据
    setCookie('special_car', null, true);
    delCookie('special_car'); //删除特价水果cookie值
    product_special.join_special_car = {}; //清除已选上的特价水果
    clearTimeout(product_special.teming_car); //定时器中止
    clearTimeout(product_special.teming_car_tips); //定时器中止
    clearTimeout(product_special.repeat_clear_opreta); //定时器中止
    product_special.teming_car = "";
    var page = $('#cart_page').val();
    if(page != 1){ //重新计算价格
        common.tongji()
    } else {
        if(cart.noCount == 0) {
            cart.count();
        }
    }

    //$('#cart_page').val() != 1 ? common.tongji() : cart.count();
}

product_special.user_reset_enter = function() {
    var special_car = getCookie('special_car');
    if(special_car != null) {
        product_special.clear_user_special_car_data();
        if($('#special_page').val() == 1) {
            window.location.reload();
        }
    }
}


product_special.batch_add_opera = function(data) { //抢购水果批量操作
    var special_car_str = '';
    var special_car = data.split('|');
    for (var i = 0; i < special_car.length; i++) {
        var tmp = special_car[i].split(',');
        if(special_car.length - 1 > i) {
            special_car_str += tmp[0]+',1|';
        } else {
            special_car_str += tmp[0]+',1';
        }
    }
    return special_car_str;
}

product_special.clear_submit_after_special_fruit = function() { //清空提交成功的数据
     product_special.clear_user_special_car_data();
}

product_special.recover_special_btn = function(id,title,price,kucun) { //恢复特价抢购按钮
    $('.special_fruit_kucun_'+id).html(kucun);
    var url=api_host+"/Api/Product/get_special_status";
    var openid=user.userBase.bingo_openid;
    if (openid==undefined || openid==null || openid.length==0){
        return false;
    }

    var data={ bingo_access_token:openid, bingo_openid:openid ,id:id};
    $.ajax({type:'post',url:url,data:data,dataType: 'json',async:false,success:function(result){

        if(result.status == 1 ) {
            product_special.create_special_btn(id,title,price,kucun,result.data.time_status,result.data.allow_buy);
        } else {
            tipsBox.createAlertBox(result.data);
        }
    }});
}



product_special.create_had_buy_btn = function(data) { //生成已购买按钮
    var special_car_str = '';
    var special_car = data.split('|');
    for (var i = 0; i < special_car.length; i++) {
        var tmp = special_car[i].split(',');
        var pid = product_special_list[tmp[0]].pid;
        var btn_str = '<a href="javascript:void(0);" class="minus_btn" onclick="product_special.minus_btn(\''+tmp[0]+'\',\''+tmp[1]+'\',\''+tmp[2]+'\',\'' + pid + '\')">已抢</a>';
        $('#special_fruit_btn_'+tmp[0]).html(btn_str);
        product_special.join_special_car[tmp[0]] = 1;
    }
    setCookie('special_car',data,true);
    common.tongji();
}

product_special.create_special_btn = function(id,title,price,kucun,active_status,allow_buy) { //生成特价的按钮
    if(product_special.join_special_car[id] == 1) { //用户已经加入购物车，无须处理
       return true;
    }

    var btn_str = '';
    var pid = product_special_list[id].pid;
    if(active_status != 1) { //活动没有开启
        if(allow_buy == 1 && kucun >= 1) {
           btn_str = '<a href="javascript:void(0);" onclick="product_special.add_btn(\''+id+'\',\''+title+'\',\''+price+'\',\''+pid+'\',event)">抢</a>';
        } else {
           btn_str = '<a href="javascript:void(0):;" class="grey" onclick="product_special.tips(1,\''+title+'\')">抢</a>';
        }
    }

    if(active_status == 1 && kucun <= 0) { //该特价水果抢光了
        btn_str = '<a href="javascript:void(0);" class="sale_out_btn">抢光了</a>';
    }

    if(active_status == 1 && kucun >= 1) { //用户可以抢
        if(allow_buy == 1) {
           btn_str = '<a href="javascript:void(0);" onclick="product_special.add_btn(\''+id+'\',\''+title+'\',\''+price+'\',\''+pid+'\',event)" class="add_btn">抢</a>';
        } else {
           btn_str = '<a href="javascript:void(0):;" class="grey" onclick="product_special.tips(1,\''+title+'\')">抢</a>';
        }
    }
    $('#special_fruit_btn_'+id).html(btn_str);
}

product_special.synchronous_leave_mall = function(data) { //同步离开商城
     for (var k in data) {
         var pid = product_special_list[data[k].id].pid;
        if(parseInt(data[k].kucun) >=1 ){
            var btn_str = '<a href="javascript:void(0);" class="add_btn" onclick="product_special.add_btn(\''+data[k].id+'\',\''+data[k].title+'\',\''+data[k].price+'\',\''+pid+'\')">抢</a>';
            $('#special_fruit_btn_'+data[k].id).html(btn_str);
            delete product_special.join_special_car[data[k].id];
        } else {
            var btn_str = '<a href="javascript:void(0);" class="sale_out_btn">抢光了</a>';
            $('#special_fruit_btn_'+data[k].id).html(btn_str);
            delete product_special.join_special_car[data[k].id];
        }
     }
}

product_special.special_car = function(id,title,num,price){ //抢购水果购物车
    var special_car = getCookie('special_car');
    if (special_car !== null && special_car != ''){
        special_car = special_car.split('|');
    }else{
        special_car = new Array();
    }
    var has = false;
    for (var i = 0; i < special_car.length; i++) {
        var tmp = special_car[i].split(',');
        if (tmp[0] == id) { //如果存在
            tmp[2] = num;
            tmp[3] = price;
            if (num <= 0) { //wlq 如果数量为0，删除cookeies
                special_car.splice(i,1);
            }else {
                special_car[i]=tmp.join(',');
            }
            has = true;
            break;
        }
    }
    if(!has && num>0){
        special_car.push(id+','+title+','+num+','+price);
    }
    special_car = special_car.join('|');
    setCookie('special_car',special_car,true);
}


//倒计时
product_special.daojishi = function(next_time,serverTime){
    var myDate = new Date();
    var next_str=myDate.getFullYear()+"/"+(myDate.getMonth()+1)+"/"+myDate.getDate()+" "+next_time+":00";
    var t=(new Date(next_str)).getTime()/1000;
    var now = serverTime;
    if (isNaN(t) || isNaN(now)){
        alert("时间出错了");
        return false;
    }
    if(t < now){
        t += 86400;
    }
    if(daojstt){
        clearTimeout(daojstt);
        daojstt=null;
        delete daojstt;
        $('#djs1').html('');
    } else {
        setTimeout(jsq,1000);
    }

    var Times = t - now;
    var online_show = 0;
    function jsq(){
        if (Times >= 0){
            var D = parseInt(Times / 86400);
            var H = parseInt((Times - D * 86400)/3600);
            var i = parseInt((Times -D * 86400 - H * 3600) / 60);
            var s = Times - H * 3600-i * 60-D * 86400;
            var html = '';
            if(Times < 600 && online_show == 0) {
                online_show = 1;
                $('#ten_minute_online').show();
            }
            if (D != 0) {
                html = "<strong>"+D+"天</strong><strong><em>"+H+"</em><i>小时</i></strong><strong><em>"+i+"</em><i>分</i></strong><strong><em>"+s+"</em><i>秒</i></strong>";
            } else {
                if(H != 0){
                    html = "<strong><em>"+H+"</em><i>小时</i></strong><strong><em>"+i+"</em><i>分</i></strong><strong><em>"+s+"</em><i>秒</i></strong";
                } else {
                    if(i != 0){
                        html = '<strong><em>'+i+'</em><i>分<i></strong><strong><em>'+s+'</em><i>秒</i></strong>';
                    } else {
                        html = '<strong><em>'+s+'</em><i>秒</i></strong>';
                    }
                }
            }
            $('#djs1').html(html);
            Times--;
            clearTimeout(daojstt);
            daojstt = setTimeout(jsq,1000);
        } else {
            clearTimeout(daojstt);
            var name = $('#next_active_name').html();
            var id = $('#next_active_id').val();
            $('#now_active_name').html(name);
            $('#special_now_active div.special-btn-box a').each(function(){
                var hasClass = $(this).attr('class');
                var id = $(this).parent().attr('id').replace('special_fruit_btn_','');
                var kucun = parseInt($('.special_fruit_kucun_'+id).html());
                if(hasClass == null || hasClass == '') {
                    if(kucun > 0) {
                        $(this).attr('class','add_btn');
                    } else {
                        $(this).attr('class','sale_out_btn');
                        $(this).html('抢光了');
                    }
                }
            });

            product_special.daojishi_over_status = 1;
            $('#special_menu_0'+id).attr('class','');
            $('#special_menu_0'+id).addClass('status1');
            $('#special-read-start-box').hide();
            $('#next_active_info_box').hide();
            $('#special-start-box').show();
        }
    }
    jsq();
};

product_special.tips = function(status,title) { //限购提示
    var tips = '';
    switch(status) {
        case 1:
            tips = title+"是限购商品，不能买再多了";
            break;
        default:
            tips = '马上就开始了，请不要走开哦';
    }
    alertBox('.alert-box',tips);
}

product_special.createConfirmBox = function() { //生成同意提示框
    home.my_cart_hide();    //购物车处理
    var alertBox = 0;
    var right_btn = '';
    var buycar = getCookie('buycar');
    var cart_page = $('#cart_page').val();
    var tips = '很抱歉，来晚啦，你的闪购商品结算超时，请重新选择商品或者';
    if(buycar != null && cart_page != 1) {
        tips += '去结算正价商品。';
        right_btn = '<a href="javascript:void(0);" onclick="tipsBox.dynamicFunction(\'product_special.regain_select_special_fruit\',\'2\')">去结算</a>';
    } else {
        tips += '继续操作。';
        if($('#special_page').val() == 1) {
            right_btn = '<a href="javascript:void(0);" style="color: #757575">继续操作</a>';
        } else {
            right_btn = '<a href="javascript:void(0);" onclick="tipsBox.dynamicFunction(\'product_special.regain_select_special_fruit\',\'3\')">继续操作</a>';
        }
    }
    var html = '<div class="confirm-wrap"><h3>'+tips+'</h3><table border-collapse="0" border-spacing="0"><tr><td><a href="javascript:void(0);" onclick="tipsBox.dynamicFunction(\'product_special.regain_select_special_fruit\',\'1\')">重选商品</a></td><td>'+right_btn+'</td></tr></tabel></div></div>';

    if( buycar == null && cart_page == 1) {
        alertBox = 1;
        tips = '很抱歉，来晚啦，你的闪购商品结算超时，去商城继续购物';
        html = '<div class="alert-wrap"><h3>'+tips+'</h3><p><a href="javascript:void(0);" onclick="tipsBox.dynamicFunction(\'product_special.regain_select_special_fruit\',\'4\')">确定</a></p></div>';
    }

    $(tipsBox.container).html(html);
    $(tipsBox.container).show();
    if(alertBox  == 1) {
       tipsBox.tipsBoxCenter(tipsBox.container + ' > div.alert-wrap');
    } else {
       tipsBox.tipsBoxCenter(tipsBox.container + ' > div.confirm-wrap');
    }

}


product_special.regain_select_special_fruit = function(status) { //抢购超时，重新选择水果
    switch(parseInt(status)) {
        case 1:
            window.location.href = '#/product_special';
            tipsBox.hideTipsBox();
            break;
        case 2:
            window.location.href = '#/cart/0';
            tipsBox.hideTipsBox();
            break;
        case 3:
            tipsBox.hideTipsBox();
            break;
        case 4:
            window.location.href = '#/home';
            tipsBox.hideTipsBox();
            break;
    }

}





/**
 * 称重产品多重量购买
 */
var product_weighing = {};
product_weighing.productData = [];    //称重产品数据
// product_weighing.productData = [{"id":id,"pxid":pxid,"name":product_item.title,"weight":weight,"price":price,'thu_img':product_item.thu_img},{"id":id,"pxid":pxid,"name":product_item.title,"weight":weight,"price":price,'thu_img':product_item.thu_img}];    //称重产品数据
product_weighing.pageX = 0;     //购买动画X轴起始位置
product_weighing.pageY = 0;		//购买动画Y轴起始位置

/**
 * 商城首页称重产品点击购买
 * @method product_weighing.plusBtn
 * @param {Number} id 产品id
 * @param {Object} event event对象
 */
product_weighing.plusBtn = function(id,event){
	if(!product_weighing.checkBuy(id)){
		return false;
	}
	if(event != undefined){
		product_weighing.pageX = event.pageX;
		product_weighing.pageY = event.pageY;
	}

	var productWeighing = product_list[id];
	common.renderTpl("#product-weighing","./product/product_weighing",productWeighing);
	$('#product-weighing').show();
	if(event == undefined){
		product_weighing.currentWeight();
	}
}

/**
 * 产品详情页称重产品购买
 * @method product_weighing.productViewPlusBtn
 * @param {Number} id 产品id
 */
product_weighing.productViewPlusBtn = function(id){

	if(!product_weighing.checkBuy(id)){
		return false;
	}

	product_weighing.pageX = 0;
	product_weighing.pageY = 0;

	var productWeighing = product_list[id];
	common.renderTpl("#product-weighing","./product/product_weighing",productWeighing);
	$('#product-weighing').show();
	product_weighing.currentWeight();
}

/**
 * 检查产品是否可以购买
 * @method product_weighing.checkBuy
 * @param {String} id 产品id
 * @return {Boolean}
 */
product_weighing.checkBuy = function(id){
	var p = product_list[id];

	//新用户专享
	if(user.is_new_user == 0 && product_list[id]['for_new_user'] == 1) {
	    tipsBox.createAlertBox(product_list[id]['title']+'是新用户专享哦~');
	    return false;
	}
	if (user.userBase.user_type == 0 && p.pid == _new_user_product_id){
	    tipsBox.createConfirmBox('关注缤果水果才能购买该产品,现在去关注?','voucherview.go_voucher',0,'确定');
	    return false;
	}
	if (user.is_new_user == 0 && p.pid == _new_user_product_id){
	    tipsBox.createAlertBox('新用户才能购买此款产品，新用户指之前没有在缤果下过订单的用户');
	    return false;
	}
	return true;
}

/**
 * 关闭称重产品重量选择按钮
 * @method product_weighing.closeBtn
 */
product_weighing.closeBtn = function(){
	$('#product-weighing').html('').hide();
}

/**
 * 确认提交选择的重量
 * @method product_weighing.sureBtn
 * @param {Number} id 产品id
 * @param {Object} event event对象
 */
product_weighing.sureBtn = function(id){
	var product_item = product_list[id];
	var sum =  parseInt($('#cart_num').text());     //购物车产品总数
	if(product_item.num != undefined || product_item.num != null){
		var num = product_item.num;
	}else{
		var num =  0;     //选择了几个产品
	}
	var subtract = 0;     //减少了几个产品
	var thisnum = 0;
	$(".weighing-list ul li").each(function(index){
    	// var price = $(this).data('price');
    	// var pxid = $(this).data('id');
    	// var weight = $(this).find('a').html();

    	// //检查全局变量中是否存在该重量的产品
    	// var arr_num = product_weighing.checkObj(pxid);

	    // if($(this).hasClass('current')) {
	    // 	if(arr_num < 0){    //没有这个重量的产品
		   //  	product_weighing.productData.push({"id":id,"pxid":pxid,"name":product_item.title,"weight":weight,"price":price,'thu_img':product_item.thu_img,"allow_voucher":product_item.allow_voucher});
		   //  	sum++;
	    // 	}
	    // 	num++;
	    // }else{
	    // 	if(arr_num >= 0){    //有这个产品，删除
	    // 		product_weighing.productData.splice(arr_num,1);
	    // 		subtract++;
	    // 	}
	    // }

    	var price = $(this).data('price');
    	var pxid = $(this).data('id');
    	var weight = $(this).find('a').html();

    	//检查全局变量中是否存在该重量的产品
    	var arr_num = product_weighing.checkObj(pxid);

	    if($(this).hasClass('current')) {
	    	if(arr_num < 0){    //没有这个重量的产品
	    		price = base.setNumberDecimals(price);
		    	product_weighing.productData.push({"id":id,"pxid":pxid,"name":product_item.title,"weight":weight,"price":price,'thu_img':product_item.thu_img,"allow_voucher":product_item.allow_voucher});
		    	sum++;
	    	}
	    	num++;
	    	thisnum++;
	    }
	});
	var totalNum = parseInt(sum) - parseInt(subtract);

	product_item.num = num;      //写入该产品数量

	var totalPrice = 0;
	for(var i = 0; i < product_weighing.productData.length; i++){
		totalPrice += product_weighing.productData[i].price;
	}
	// product_item.totalPrice = $('#weighing-totalprice').html();    //写入价格
	product_item.totalPrice = base.setNumberDecimals(totalPrice);    //写入价格

	product_weighing.closeBtn();    //关闭弹出窗
	//产品列表显示用户购买情况
	if(num == 0){
		show_user_buy(product_item,'');
	}else{
		show_user_buy(product_item,'load');
	}
	common.tongji();
	if(totalNum != 0){
		$("#cart_num").show().text(totalNum);     //写入购物车数量
	}else{
		$("#cart_num").text(totalNum).hide();     //写入购物车数量
	}
    //购买动画
    if(product_weighing.pageX != 0 && product_item.num != 0 && thisnum > 0){
	    // setTimeout("animateCart('" + product_item.thu_img + "','','" + product_weighing.pageX + "','" + product_weighing.pageY + "')",500);
	    animateCart(product_item.thu_img, '', product_weighing.pageX, product_weighing.pageY);
	 //    product_weighing.pageX = 0;     //购买动画X轴起始位置
		// product_weighing.pageY = 0;		//购买动画Y轴起始位置
    }
}

/**
 * 检查全局变量中是否已存在该重量的产品
 * @method product_weighing.checkObj
 * @return {Number}
 */
product_weighing.checkObj = function(pxid){
	var data_type = [];
	$.each(product_weighing.productData, function(i){
	    data_type.push(product_weighing.productData[i].pxid);
	});
	var arr_num = $.inArray(pxid, data_type);

	return arr_num;
}

/**
 * 选中全局变量中已存在的该产品的重量
 * @method product_weighing.currentWeight
 */
product_weighing.currentWeight = function(){
	// var totalPrice = 0;
	$(".weighing-list ul li").each(function(){
    	var pxid = $(this).data('id');
    	var price = parseFloat($(this).data('price'));
    	//检查全局变量中是否存在该重量的产品
    	var arr_num = product_weighing.checkObj(pxid);
    	if(arr_num >= 0){    //有这个重量的产品
    		$(this).addClass('discurrent');
    		// totalPrice = (Number(totalPrice) + price).toFixed(2);
    	}
	});
	// $('#weighing-totalprice').html(totalPrice);
}

/**
 * 选择一个重量
 * @method product_weighing.selectWeight
 * @param {Object} this dom
 */
product_weighing.selectWeight = function(_this){
	if(_this.hasClass('discurrent')){
		return false;
	}
	var itemPrice = parseFloat(_this.data('price'));
	// var totalPrice = parseFloat($('#weighing-totalprice').html());
	// console.log(totalPrice,itemPrice);
	if(_this.hasClass('current')){
		//减法
		// var price = (totalPrice - itemPrice).toFixed(2);
	}else{
		//加法
		// var price = (totalPrice + itemPrice).toFixed(2);
	}
	var price = base.setNumberDecimals(itemPrice);
	// console.log(price);
	$('#weighing-totalprice').html(price);

	$(".weighing-list ul li").each(function(){
		$(this).removeClass('current');
	});
	_this.toggleClass('current');
}

/**
 * 商城首页底部购物车删除一个称重产品
 * @method product_weighing.deleteWeight
 * @method {number} id 称重产品id
 * @param {String} pxid 称重产品副id
 */
product_weighing.deleteWeight = function(id,pxid){
	var product_item = product_list[id];
	var arr_num = product_weighing.checkObj(pxid);
	if(arr_num >= 0){    //有这个产品，删除
		product_weighing.productData.splice(arr_num,1);
		$('#iteminfo-' + pxid).remove();
		var cart_num = parseInt($('#cart_num').html()) - 1;
		$('#cart_num').html(cart_num);
		//关闭购物车
		if(cart_num == 0){
			home.my_cart_hide();
		}
		//产品总数量减一
		product_item.num--;
		//写入新的产品总价
		var price = 0;
		for(var i = 0; i < product_weighing.productData.length; i++){
			if(product_weighing.productData[i].id == id){
				price += parseFloat(product_weighing.productData[i].price);
			}
		}
		product_item.totalPrice = base.setNumberDecimals(price);

		if(product_item.num == 0){
			//数量为0改变列表中的状态
			show_user_buy(product_item);
		}else{
			show_user_buy(product_item,'load');
		}

		common.tongji();
	}else{
		tipsBox.createAlertBox("删除产品失败，请重试");
	}
}

/**
 * 购物车询问是否删除一个称重产品
 * @method product_weighing.cartDeleteWeight
 * @param {String} pxid 称重产品副id
 */
product_weighing.cartDeleteWeight = function(pxid){
	tipsBox.createConfirmBox('您确定将这款商品从购物车里删除吗？','product_weighing.sureCartDeleteWeight',pxid,'确定');
}

/**
 * 确定从购物车删除一个称重产品
 * @method product_weighing.sureCartDeleteWeight
 * @param {String} pxid 称重产品副id
 */
product_weighing.sureCartDeleteWeight = function(pxid){
	var arr_num = product_weighing.checkObj(pxid);
	if(arr_num >= 0){    //有这个产品，删除
		product_weighing.productData.splice(arr_num,1);
		$('#goods-' + pxid).remove();
		tipsBox.hideTipsBox();
		var buycar = getCookie('buycar');
		if(buycar != null && buycar != undefined){
			var all_p = buycar.split("|");
			if (all_p == "" && product_weighing.productData.length == 0){
			    window.location.href="#/home";
			    return false;
			}
		}else{
			if (product_weighing.productData.length == 0){
			    window.location.href="#/home";
			    return false;
			}
		}
		//重新统计费用
		cart.count_show(0,0,"");
		cart.count();
	}else{
		tipsBox.createAlertBox("删除产品失败，请重试");
	}
}

/**
 * cookie的buycart添加上称重产品
 * @method product_weighing.buycartAddWeights
 * @param {String} buycar 购物车cookie
 */
product_weighing.buycartAddWeights = function(buycar){
    if(buycar == null){
        buycar = "";
    }
    var data = product_weighing.productData;
    var len = product_weighing.productData.length;
    if(len > 0){
        for(var i = 0; i < len; i++){
            if(buycar == ""){
                buycar += data[i].id + "," + data[i].name + "," + "1" + "," + data[i].price + "," + data[i].weight;
            }else{
                buycar += "|" + data[i].id + "," + data[i].name + "," + "1" + "," + data[i].price + "," + data[i].weight;
            }
        }
    }
    return buycar;
}

/**
 * 在商城首页显示用户已选择的称重产品
 * @method product_weighing.showUserBuy
 */
product_weighing.showUserBuy = function(){
	var data = product_weighing.productData;
	var len = data.length;
	if(len <= 0 ){
		return false;
	}
	var yzid = [];
	for(var i = 0; i < len; i++){
		var id = data[i].id;
		var pxid = data[i].pxid;
		if($.inArray(id, yzid) < 0){   //这个id的产品还没渲染过
			yzid.push(id);
			var num = 0;
			var totalPrice = 0;
			for(var k in data){
				if(data[k].id == id){
					num++;
					totalPrice += data[k].price;
				}
			}
			var product_item = product_list[id];
			product_item.num = num;
			product_item.totalPrice = base.setNumberDecimals(totalPrice);
			show_user_buy(product_item,'load');
		}
	}
}


/**
 * 称重计算
 * @method product_weighing.countWeights
 * @param {String} type 商品类型
 * @param {String} price 价钱
 * @param {object} data 称重数据
 * @param {String} mark 称重标识
 * @returns {String}
 */
product_weighing.countWeights = function(type, price, data, mark) {
	var weights = data || '';
	if(weights == '' || mark != '称重' || type != 'normal') {
		return base.setNumberDecimals(price);
	}
	if(data.length == 1) {
		return base.setNumberDecimals(weights[0].totalprice);
	} else {
		var dataList = [];
		for(var j = 0; j < data.length; j++) {
			if(j < 6) {
				dataList.push(data[j].totalprice);
			}
		}
		var minValue = base.setNumberDecimals(Math.min.apply(null,dataList));
		var maxValue = base.setNumberDecimals(Math.max.apply(null,dataList));
		if(minValue == maxValue ) {
			return maxValue;
		} else {
			return minValue + "~" + maxValue;
		}
	}
}
/**
 * 产品回溯
 * 通过条形码，获得产品的详细信息
 */
var scan_code = {};

/**
 * 扫码用户登陆
 * @param {Number} id 条型码id
 * @returns {boolean}
 */
scan_code.oauthLogin = function(id) {
    if(user.islogin == 1) {
        scan_code.getBarcodeData(id);
        return false;
    }

    var url = api_host + "/Api/Users/oauth_login";
    var openid = user.userBase.bingo_openid;
    var data = { bingo_secret: 'fb92390dd7c59c3fcb4fcce4801aadecb79f2e4a', bingo_appid: config.appid , oauth_type: 4, oauth_openid: openid };
    $.ajax({type: 'post', url: url, data: data, dataType: 'json', success: function(result){
        if(result.status == 1) {
            user.userBase = result.data;
            scan_code.getBarcodeData(id);
        } else {
            tipsBox.createAlertBox(result.data);
        }
    }});
}

/**
 * 获得条形码数据
 * @method scan_code.getBarcodeData
 * @param {Number} id 条型码id
 * @returns {boolean}
 */
scan_code.getBarcodeData = function(id) {
    var url = api_host+"/Api/Product/scan_barcode";
    var openid = user.userBase.bingo_openid;
    if (openid==undefined || openid==null || openid.length==0){
        return false;
    }
    var data={ bingo_access_token:openid ,bingo_openid:openid,bingo_appid:config.appid,barcode:id };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        if(result.status != 1) {
            window.location.href = '#/bingo_code';
            return false;
        }

        common.renderTpl("#app_content",'scan_code/barcode',result.data);
        common.loaded(1);

        var click = '';
        var buy_btn = '我也要买一份';
        var url = 'javascript:void(0);';

        if(result.data.is_me == 1) {
            buy_btn = '我要再买一份';
        }

        if(result.data.product_status == 1 && result.data.league_id == user.userBase.league_id ) {
             url = scan_code.getProductUrl(result.data.product_id, result.data.product_type);
        } else {
            var tips = '这款产品已经下架啦~<br/>去商城逛逛别的吧!';
            click = "tipsBox.createAlertBoxAll(\'"+tips+"\',\'去缤果商城\',\'"+config.pathUrl+"\',\'tc\')";
        }

        if($('.barcode-process-main ul').children().length >= 2) {
            $('.barcode-process-border').show();
        }

        navigation.commonFooterTpl(buy_btn, url, click);
    }});
}

/**
 * 缤果条形码
 * @method scan_code.bingoCode
 */
scan_code.bingoCode = function() {
    common.renderTpl('#app_content','scan_code/bingo_code',{});
    common.loaded(1);
}


/**
 * 获得产品的url
 * @method scan_code.getProductUrl
 * @param {Number} id 产品id
 * @param {String} type 类型
 * @returns {string}
 */
scan_code.getProductUrl = function(id,type) {
    switch ((parseInt)(type)) {
        case 0: //正常水果
            if(user.userBase.league_id != undefined || user.userBase.league_id != '') {
                return '#/product_view/normal/'+id;
            } else {
                return '#/home';
            }
            break;
        case 1: //团购
            return '#/product_special';
            break;
        case 2: //特价
            return '#/product_special';
            break;
        default:
            return '#/home';
    }
}

/**
 * 调用微信扫码
 * @method scan_code.scan_btn
 */
scan_code.scan_btn = function() {
    wx.scanQRCode({
        needResult: 1,
        desc: '扫一扫缤果商品包装上的条形码          即可获取该商品更多详细信息',
        success: function (result) {
            var id = 0;
            if(result.errMsg == 'scanQRCode:ok') {
                if (browser.versions.iPhone || browser.versions.iPad || browser.versions.ios) {
                    var result = JSON.parse(result.resultStr);
                    id = (result.scan_code.scan_result).split(',')[1];
                } else {
                    id = result.resultStr.split(',')[1];
                }

                if(id != 0) {
                    window.location.href = '#/scan_code/'+id;
                    return true;
                }
            }
            tipsBox.createAlertBox("扫码失败");
        }
    });

    //按钮点击统计
    common.buttonClikcStatistics("scan","scan_scan","立即扫一扫");
}

/**
 * 扫码教程
 * @method scan_code.scanCourse
 */
scan_code.scanCourse = function() {
    common.renderTpl('#app_content','scan_code/scan_course',{});
    common.loaded(1);
}

/**
 *积分
 */
//购买指定产品加1 +1
var exchange = {}
exchange.show_my_exchange = function() {
    exchange.gift_list();
    exchange.score_record();
    exchange.change_record();
    common.loaded(1);
}

exchange.show_exchange = function(tabName) { //显示兑换页面
    var html = template('exchange', {});
    $("#app_content").html(html);
    common.user_login(exchange.show_my_exchange);
    exchange.selectedTabBox(tabName);
}

exchange.gift_list = function() { //兑换礼品数据
    var openid = user.userBase.bingo_openid;
    var url = api_host+"/Api/Score/score_gift_list";
    var data = { bingo_access_token:openid,bingo_openid:openid };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        $('#user_score').html(result.data.user_score);
        user.userBase.score_sum = result.data.user_score;
        if (result.data.list.length > 0) {
            var html = template('exchange_gift', result);
            $("#integral-exchange").html(html);
        }else{
            $("#exchange_no_gift").show();
        }
    }});
}

exchange.score_record = function() { //用户积分
    var openid = user.userBase.bingo_openid;
    var url = api_host+"/Api/Score/score_record";
    var data = { bingo_access_token:openid, bingo_openid: openid };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        if (result.data.length > 0) {

            var html = template('exchange_score_record', result);
            $("#my-integral").html(html);
        }else{
            $("#my-no-integral").show();
        }
    }});
}

exchange.change_record = function() { //用户兑换记录
    var openid = user.userBase.bingo_openid;
    var url = api_host+"/Api/Score/score_change_record";
    var data = { bingo_access_token:openid, bingo_openid: openid };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        if (result.data.length > 0) {
            var html = template('exchange_change_record', result);
            $("#exchange-prize").html(html);
        }else{
            $("#exchange-no-prize").show();
        }
    }});
}

exchange.show_prizeview = function(id) { //显示礼品详细页面
    var url = api_host+"/Api/Score/score_gift_view";
    var openid = user.userBase.bingo_openid;
    if (openid == undefined || openid == null || openid.length == 0){
        return false;
    }
    var data = { "bingo_access_token" : openid,"gift_id" : id};
    $.ajax({type:'post',url:url,data:data,dataType: 'json', async:false, success:function(data){
        var prize = data.data;
        var html = template('prizeview', prize);
        $("#app_content").html(html);
        if(data.data.type == 0) {
            $('#prizeview-content').html(data.data.content);
        } else {
            $('#prizeview-content').html(data.data.info);
        }
        $('.prizeview-content img').css('width','100%');
        render_user();

        common.loaded(0);
        navigation.simpleStyle(prize.title);   //设置头部标题
        var need_score = common.numFormat(prize.need_score);
        //设置底部按钮
        if(prize.type == 1){
            navigation.commonFooterTpl("兑换（" + need_score + "积分）", "#/prize/" + prize.id + "");
        }else{
            navigation.commonFooterTpl("兑换（" + need_score + "积分）", "javascript:void(0);","exchange.userExchangeCode('" + prize.id + "','" + prize.title + "','" + need_score + "','" + prize.type + "')");
        }

    }});
}

exchange.show_prize = function(id) { //显示实物兑换页面
    var url = api_host+"/Api/Score/score_gift_view";
    var openid = user.userBase.bingo_openid;
    if (openid == undefined || openid == null || openid.length == 0){
        return false;
    }
    var data = { "bingo_access_token" : openid,"gift_id" : id};
    $.ajax({type:'post',url:url,data:data,dataType: 'json', async:false, success:function(data){
        var prize = data.data;
        var html = template('prize', prize);
        $("#app_content").html(html);
        render_user();

        common.loaded(0);

        navigation.simpleStyle(prize.title);        //设置头部标题
        navigation.commonFooterTpl("确认兑换", "javascript:void(0);","exchange.sureExchange('" + prize.id + "','" + prize.title + "')");   //设置底部按钮

    }});
}

exchange.selectedTabBox = function(tabName) { //兑换Tab菜单
    $('.exchange-menu li').removeClass('current');
    $('#'+tabName+'-tab').addClass('current');
    $('.'+tabName).show();
    $('.'+tabName).siblings().hide();
}

exchange.userExchangeCode = function(id, title, score, type) { //兑换代金券
    var totalScore = parseInt($('#user_score').html());
    var score = parseInt(score);
    if(score > totalScore) {
        alertBox('.alert-box','积分不够哦~');
        return false;
    }
    $('#exchange-gift-name').html(title);
    $('#exchange-gift-score').html(common.numFormat(score));
    $('#exchange-yes').data('id',id);
    $('#exchange-yes').data('type',type);
    $('#exchange-windows-wrap').show();
    tipsBoxCenter('.exchange-windows-inner');
}
exchange.exchangeNo = function() { //用户取消兑换
    $('#exchange-gift-name').html('');
    $('#exchange-gift-score').html('');
    $('#exchange-yes').data('id','');
    $('#exchange-windows-wrap').hide();
}

exchange.exchangeYes = function() { //用户确定兑换
    var id =  $('#exchange-yes').data('id');
    var type = $('#exchange-yes').data('type');
    var title = $('#exchange-gift-name').html();
    exchange.exchangeOpera(id,title,type,'','','','');
}

exchange.sureExchange = function(id,title) { //用户确定兑换
    var name = $('#user-exchange-name').val();
    var tel = $('#user-exchange-tel').val();
    var address = $("#user-exchange-address").val();
    var mark = $("#user-exchange-mark").val();
    if(name == '') {
        alertBox('.alert-box','请输入收件人名字');
        return false;
    }
    if(tel == '') {
        alertBox('.alert-box','请输入收件人电话');
        return false;
    }
    if(address == '') {
        alertBox('.alert-box','请输入收件人详细地址');
        return false;
    }
    exchange.exchangeOpera(id,title,1,name,tel,address,mark);
}

exchange.scoreTips = function(id,score) { //能不能兑换礼品
    var totalScore = parseInt($('#user_score').html());
    var score = parseInt(score);
    if(score > totalScore) {
        alertBox('.alert-box','积分不够哦~');
        return false;
    }
    window.location.href = '#/prize/'+id;
}

exchange.exchangeOpera = function(id,title,type,name,tel,address,mark) { //兑换操作
    var url = api_host+"/Api/Score/score_change";
    var openid = user.userBase.bingo_openid;
    if (openid == undefined || openid == null || openid.length == 0){
        return false;
    }
    var data = {
        "bingo_access_token": openid
        ,"bingo_openid": openid
        ,"bingo_appid": config.appid
        ,"gift_id": id
        ,"name": name
        ,"tel": tel
        ,"address": address
        ,"mark": mark
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json', async:false, success:function(data){
        if(data.status == 1) {
            if(type == 2) {
                alertBox('.alert-box',title+"兑换成功,请在您接收到的微信消息中查看详情。");
            } else {

                alertBox('.alert-box',title+"兑换成功");
            }
            var gift_score  = $('#exchange-gift-score').html();
            var remain_score = parseFloat(user.userBase.score_sum) - parseFloat(gift_score);
            user.userBase.score_sum = remain_score;
            $('#user_score_sum').html(common.numFormat(user.userBase.score_sum));
            $('#user_score').html(remain_score);
            window.location.href="#/exchange/exchange-prize";
            $("html,body").scrollTop(0);
            exchange.change_record();
            exchange.selectedTabBox('exchange-prize');
            exchange.exchangeNo();
        } else {
            alertBox('.alert-box',data.data);
            exchange.exchangeNo();
        }
    }});
}

var recharge = {}
recharge.pay_type = '';
recharge.user_recharge = function() { //用户充值页面
    var url = api_host+"/Api/Pay/recharge_record";
    var openid = user.userBase.bingo_openid;
    if (openid == undefined || openid == null || openid.length == 0){
        return false;
    }
    var data = { "bingo_access_token" : openid, 'bingo_openid' : openid};
    $.ajax({type:'post',url:url,data:data,dataType: 'json', async:false, success:function(result){
        if(result.status == 1) {
            result.data = result.data == '' ? {} : result.data;
            var html = template('recharge', result);
            $("#app_content").html(html);
            common.loaded();

            if(_is_app != 1) {//临时关闭微信充值
                $('#weixin-recharge-box').show();
            }
            $("#header-common-main").html("&nbsp;");
        } else {
            tipsBox.createAlertBox(result.data);
        }
    }});
}

recharge.recharge_ice = function() { //用户冰结余额
    var url = api_host+"/Api/AfterSale/get_fresh_return_list";
    var openid = user.userBase.bingo_openid;
    var data = { bingo_access_token: openid, bingo_openid : openid};
    $.ajax({type:'post',url:url,data:data,dataType: 'json', async:false, success:function(result){
        if(result.status == 1) {

            if(result.data == '') {
                window.location.href = '#/recharge';
                return false;
            }
            var html = template('recharge_ice', result.data);
            $("#app_content").html(html);
            recharge.recharge_ice_jumb();
            $('.footer-table tr td.center').html('');
            $('.footer-table tr td.right').html('');
            common.loaded();

            navigation.simpleStyle("鲜赔理冻结余额");

        } else {
            tipsBox.createAlertBox(result.data);
        }
    }});
}

recharge.recharge_ice_jumb = function() {
    var status = $('#recharge-ice').val();
    if(status == '1') {
        if($('#recharge-ice-page').children().length <= 0 ) {
            window.location.href = '#/recharge';
        }
    }
}

recharge.deal_with_status = function(status) {
    switch(parseInt(status)) {
        case -3:
            return '失败';
            break;
        case -2:
            return '已取消申请';
            break;
        case -1:
            return '已拒绝申请受理';
            break;
        case 0:
            return '申请中';
            break;
        case 1:
            return '受理中';
            break;
        case 2:
            return '成功';
            break;
    }
}


recharge.showRechargeRecoder = function() {
    var status = $('#recharge-recoder').val();
    if(status == 0) {
        $('.recharge-record-wrap ul').show();
        $('#recharge-recoder').val(1);
    } else {
        $('.recharge-record-wrap ul').hide();
        $('#recharge-recoder').val(0);
    }
}

recharge.showRechargeOpera = function(pay_type) {
    recharge.pay_type = pay_type;
    $('#pay-money').val('');
    if(pay_type == 1) {
        $('.recharge-opera-inner a.sure-btn').attr('onclick','recharge.surePayMoney()');
        $('.recharge-opera-inner h1').html('请输入充值金额');
    } else {
        $('.recharge-opera-inner a.sure-btn').attr('onclick','recharge.surePayCart()');
        $('.recharge-opera-inner h1').html('请输入充值卡密码');
    }

    $('.recharge-opera-box').show();
}

recharge.hideRechargeOpera = function() { //隐藏
     $('.recharge-opera-box').hide();
}

recharge.surePayMoney = function() { //用户确定充值
    var money = $('#pay-money').val();
    if(money == '' || parseFloat(money) == 0) {
        tipsBox.createAlertBox('请输入你充值金额');
        return false;
    }
    var reg = /^\d+?$/g;
    if(!reg.test(money)) {
        tipsBox.createAlertBox('请输入1000以内的整数');
        return false;
    }
    if(money < 1 || money > 1000) {
        if(money < 1) {
            tipsBox.createAlertBox('充值最小充值1元');
        }
        if(money > 1000) {
            tipsBox.createAlertBox('充值最多充值1000元');
        }
        return false;
    }

    var url = api_host+"/Api/Pay/recharge";
    var openid = user.userBase.bingo_openid;
    if (openid == undefined || openid == null || openid.length == 0){
        return false;
    }
    var data = { bingo_access_token:openid, bingo_openid:openid, money:money,pay_type:recharge.pay_type,remark:''};
    $.ajax({type:'post',url:url,data:data,dataType: 'json', async:false, success:function(result){
        if(result.status == 1){
            if(window.location.host == 'test.bingofresh.com') {
                window.location.href = 'http://pay.bingofresh.com/wxpay_new/test_bingo_pay.php?total_fee='+money+'&orderno='+result.data.orderno+'&open_id='+openid;
            } else {
                window.location.href = 'http://pay.bingofresh.com/wxpay_new/bingo_pay.php?total_fee='+money+'&orderno='+result.data.orderno+'&open_id='+openid;
            }
        } else {
            tipsBox.createAlertBox(result.data);
        }
    }});
}

recharge.surePayCart = function() { //用户确定充值
    var card_password = $('#pay-money').val();
    if(card_password == '' || parseFloat(card_password) == 0) {
        tipsBox.createAlertBox('请输入你充值卡/券密码');
        return false;
    }
    var reg = /^\d+?$/g;
    if(!reg.test(card_password)) {
        tipsBox.createAlertBox('输入的充值卡/券密码错误');
        return false;
    }


    var url = api_host+"/Api/Pay/card_pay_recharge";
    var openid = user.userBase.bingo_openid;
    if (openid == undefined || openid == null || openid.length == 0){
        return false;
    }
    var data = { bingo_access_token:openid, bingo_openid:openid,card_password:card_password};
    $.ajax({type:'post',url:url,data:data,dataType: 'json', async:false, success:function(result){
        if(result.status == 1){
            common.user_login(recharge.user_recharge);
            tipsBox.createAlertBox('充值成功');
        } else {
            tipsBox.createAlertBox(result.data);
        }
    }});
}

/*
recharge.surePayOrder = function(oid) {//作额支付页面
    var url = api_host+"/Api/Order/get_order_data";
    var openid = user.userBase.bingo_openid;
    if (openid == undefined || openid == null || openid.length == 0){
        return false;
    }
    var data = { bingo_access_token:openid, bingo_openid:openid,order_id:oid};
    $.ajax({type:'post',url:url,data:data,dataType: 'json', async:false, success:function(result){
        if(result.status == 1){
            var html = template('sure_pay_order', result.data);
            $("#app_content").html(html);
            common.loaded(0);
            $('.cart-box-wrap').html('<a href="javascript:void(0);" class="cart-btn"  onclick="recharge.rightNowPayOrder('+oid+')">立刻支付</a>');
            $('.footer-table tr td.right').html('');
            $('.footer-table tr td.left a').attr('href','javascript:void(0);');
            $('.footer-table tr td.left a').attr('onclick','recharge.returnTips()');
            recharge.user_balance(result.data.total_fee);
        } else {
            tipsBox.createAlertBox(result.data);
        }
    }});
}*/

recharge.surePayOrder = function(oid,orderno) {//作额支付页面
    var url = api_host+"/Api/Order/get_order_data";
    var openid = user.userBase.bingo_openid;
    var data = { bingo_access_token:openid, bingo_openid:openid,order_id:oid};
    $.ajax({type:'post',url:url,data:data,dataType: 'json', async:false, success:function(result){
        if(result.status == 1){
            result.data.oid = oid;
            result.data.orderno = orderno;
            common.renderTpl("#app_content",'cart/cart_balance',result.data);
            common.loaded(0);

            $('#back-btn').attr('href','javascript:recharge.returnTips();');
            recharge.user_balance(result.data.total_fee);
        } else {
            tipsBox.createAlertBox(result.data);
        }
    }});
}


recharge.user_balance = function(total) {
    var url = api_host+"/Api/Users/user_balance";
    var openid = user.userBase.bingo_openid;
    if (openid == undefined || openid == null || openid.length == 0){
        return false;
    }
    var data = { bingo_access_token:openid, bingo_openid:openid,uid:user.userBase.id};
    $.ajax({type:'post',url:url,data:data,dataType: 'json', async:false, success:function(result){
        if(result.status == 1) {
            $('#user_balance').html(base.setNumberDecimals(result.data.money) + '元');
            if(parseFloat(total) > parseFloat(result.data.money)){
               $('#user_balance').parent().css('top','10px');
               $('#user_balance_tips').html('(余额不足)');
            }

            var reamain = 0;
            var html = '<dl class="tc" style="position: absolute; top: 0px; right: 15px;"><dt>余额:'+base.setNumberDecimals(result.data.money) + '元</dt>';
            var style = 'position: relative;  width: 120px; color: #6cbed8; padding: 0 15px';
            if(parseFloat(total) > parseFloat(result.data.money)){
                reamain = 1;
                html += '<dd style="font-size: .75em;">(余额不足)</dd>';
                style += 'padding-top: 12px; line-height: 1;';
            }
            html += '</dl>'

            $('.header-common-inner table tr td:last-child').html(html);
            $('.header-common-inner table tr td:last-child').attr('style',style);

            var width = $('.header-common-inner table tr td:last-child dl').width();
            $('.header-common-inner table tr td:last-child').css('width',width + 30);

            if(reamain){
                $('.header-common-inner table tr td:last-child dl').css('top',12);
            }
        }
    }});
}

recharge.returnTips = function() { //用户返回提示
    var tips = '宾哥提醒你，你的订单已生成，但未支付成功，为你的订单保留12小时，超过12个小时订单会自动取消喔！';
    tipsBox.createConfirmBox(tips, 'tipsBox.hideTipsBox', '', '继续支付');
    $('.confirm-wrap table tr td:first-child a').html('返回首页');
    $('.confirm-wrap table tr td:first-child a').attr('href','#/home');
}

recharge.rightNowPayOrder = function() {//用户确认支付
    var oid = $('#balance-oid').val();
    var url = api_host+"/Api/Pay/complete_recharge ";
    var openid = user.userBase.bingo_openid;
    if (openid == undefined || openid == null || openid.length == 0){
        return false;
    }
    var data = { bingo_access_token:openid, bingo_openid:openid,order_id:oid};
    $.ajax({type:'post',url:url,data:data,dataType: 'json', async:false, success:function(result){
        if(result.status == 1){
            window.location.href = '#/complete/'+ user.userBase.id +'/'+oid;
        } else {
            recharge.payTips(result.data+'请换一种支付方式','recharge.changePayWay',oid);
        }
    }});
}

recharge.payTips = function(tips, name, param, sure){ //提示用户选新的支付方式
    var sure  = (sure != undefined ) ? sure: '确定';
    var alipay =  '';
    var localhost = '<li><input type="radio" name="pay_type" id="pay_type0" value="0" checked="checked"><label class="round current" for="pay_type0"></label><label for="pay_type0"> 货到付款</label></li>';
    var weixin  = '<li><input type="radio" name="pay_type" id="pay_type1" value="1"><label class="round" for="pay_type1"></label><label for="pay_type1"> 微信安全支付</label></li>';
    if(_is_app == 1) {
         alipay = '<li><input type="radio" name="pay_type" id="pay_type2" value="2"><label class="round" for="pay_type2"></label><label for="pay_type2"> 支付宝支付</label></li>';
    }
    var pay_list = '<div class="play-box"><ul class="pay_way_list">'+localhost+weixin+alipay+'</ul></div>';
    var html = '<div class="confirm-wrap"><h3>'+tips+'</h3>'+pay_list+'<table border-collapse="0" border-spacing="0"><tr><td><a href="javascript:void(0);" onclick="tipsBox.hideTipsBox()">取消支付</a></td><td><a href="javascript:void(0);" onclick="tipsBox.dynamicFunction(\''+name+'\',\''+param+'\')">'+sure+'</a></td></tr></tabel></div></div>';
    $(tipsBox.container).html(html);
    $(tipsBox.container).show();
    tipsBox.tipsBoxCenter(tipsBox.container + ' > div.confirm-wrap');
}

recharge.changePayWay = function(oid) { //用户改变支付方式
    var orderno = $('#balance-orderno').val();
    var openid = user.userBase.bingo_openid;
    var url = api_host+"/Api/Order/order_operate";
    var type = $('input[name="pay_type"]:checked').val();
    var pay_type = '';
    switch (parseInt(type)) {
        case 0:
            type = 'changetype';
            break;
        case 1:
            type = 'wxpay';
            break;
        case 2:
            type = 'alipay';
            break;
        case 3:
            type = 'balance_type';
            break;
    }
    var data = { bingo_access_token:openid, order_id:oid,type:type};
    $.ajax({type:'post',url:url,data:data,dataType: 'json', async:false, success:function(result){
        if(result.status == 1){
            switch(type) {
                case 'changetype':
                    tipsBox.hideTipsBox();
                    window.location.href = '#/complete/'+user.userBase.id+'/'+oid;
                break;
                case 'wxpay':
                    switch (parseInt(_is_app)) {
                        case 0:
                            var host = window.location.host;
                            if (host  == "test.bingofresh.com"){//测试服务器
                                window.location.href='http://pay.bingofresh.com/wxpay_new/callpayjs.php?is_test=1&showwxpaytitle=1&order_id='+oid;
                            } else if (host == "m.bingofresh.com" || host == "m2.bingofresh.com"){//正式服务器
                                window.location.href='http://pay.bingofresh.com/wxpay_new/callpayjs.php?showwxpaytitle=1&order_id='+oid+'&open_id='+user.userBase.bingo_openid;
                            }
                            break;
                        case 1:
                            var host = window.location.host;
                            if (host  == "test.bingofresh.com"){//测试服务器
                                window.location.href='http://pay.bingofresh.com/wxpay_new/App_WxPay.php?is_test=1&order_id=' + oid + '&platform=' + config.appid;
                            } else if (host == "m.bingofresh.com" || host == "m2.bingofresh.com"){//正式服务器
                                window.location.href='http://pay.bingofresh.com/wxpay_new/App_WxPay.php?order_id=' + oid + '&platform=' + config.appid;
                            }
                            break;
                    }
                    break;
                case 'alipay':
                    window.location.href = '#/aliPay/'+oid+'/'+orderno;
                    break;
                case 'balance_type':
                    window.location.href = '#/sure_play/'+oid;
                    break;
            }

        } else {
            tipsBox.createAlertBox(result.data);
        }
    }});
}
/*
 * 商城搜索功能
 * create time: 2015/11/30
 * author: 亮
 */
var search = {};
search.keyWord = ''; //关键字
search.product = {}; //搜索数据
search.searchAutoPlan = null; //自动查找任务
search.reloadPage = function(type) { //防止不页面不跳转，自动刷新页面
    var url = window.location.href;
    if(type == 1 &&  url.indexOf('#/product_special') != -1) {
        window.location.reload();
        return false;
    }

    if(type == 1) {
        window.location.href = '#/product_special';
        return false;
    }

    window.location.reload();
    return false;
}

search.searchResults = function(key_word,renderer_type) { //查找合适的水果
    if(common.isOwnEmpty(product_list)) {
        var url = api_host+"/Api/Product/product_list";
        var openid = user.userBase.bingo_openid;
        var branch_id = 0;
        if(user.userBase.branch_id !== "") {
            branch_id = user.userBase.branch_id;
        }
        var data = {
            bingo_access_token: openid
            ,bingo_openid: openid
            ,league_id: user.userBase.league_id
            ,branch_id: branch_id
            ,app_id:config.appid

        };

        $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
            home.productData = result;
            home.cate_id = 0;
            for(var i in result.data.product) {
                product_list[result.data.product[i]["id"]] = result.data.product[i];
            }

            home.set_group_data(result.data.groupbuy);
            home.banner = result.data.banner;
            search.renderer(key_word,renderer_type);
        }});
    } else {
        search.renderer(key_word,renderer_type);
    }
}

search.renderer = function(key_word,renderer_type) { //导入搜索页面
    var data = {};
    data.product = {};
    for (var k in product_list) {
        if(product_list[k].title.indexOf(key_word) != -1) {
            data.product[product_list[k]['id']] = product_list[k];
        }
    }
    search.rendererTpl(data.product,key_word,renderer_type);
}

search.rendererTpl = function(product,key_word,renderer_type) {
    var data = {};
    search.product = product;
    data.product = product;
    data.product_group_list = product_group_list;
    data.img_v = _img_v;
    data.GL_SELECTED = GL_SELECTED;
    data.result = common.isOwnEmpty(data.product) ? 1 : 0;
    data.banner = home.banner;

    var html = template('search', data);
    $("#app_content").html(html);

    if(data.result) {
        $('.no-data').show();
    } else {
        $('.copyright').show();
        $('.footer-banner').show();
    }
    $('#key-word').val(key_word);
    $('#key-word').css('color','#454545')
    search.changeSearchModel(1);
    common.loaded(2);
    home.product_list_position();
    if(renderer_type == 1) {
        $("#key-word").focus();
        if(data.result) {
            $('.no-data').show();
        }
    }
}

search.changeSearchModel = function(type, status) { //切换成搜索模式
    $('#home_nav').hide();
    $('#search-btn').hide();
    $('#search-box').hide();
    $('#fruit-btn').hide();
    $('.product-mune table tr td.second-children').removeAttr('style');

    switch (type) {
        case 1:
            $('#fruit-btn').show();
            $('#search-box').show();
            $('.product-mune table tr td.second-children').attr('style','');
            break;
        default :
            $('#home_nav').show();
            $('#search-btn').show();
            $('.product-mune table tr td.second-children').css('width','60px');
            if(status == 1) {
                home.show_product_tpl(home.productData,0);
                $('#li_home').attr('onclick','search.reloadPage(0)');
                $('#li_home a').attr('href','javascript:void(0);');
                $('#li_product_special').attr('onclick','search.reloadPage(1)');
                $('#li_product_special a').attr('href','javascript:void(0);');
            }
            break;
    }
}

search.changeKeyWord = function() { //修改关键字
    var keyWord = $('#key-word').val();
    if(keyWord != '') {
        search.searchResults(keyWord);
        $('#key-word').css('color','#454545');
    } else {
        $('#key-word').css('color','#999');
        if($('#search-page').val() == 1) {
            search.rendererTpl(home.productData.data.product, '', 1);
        }
    }
}

search.cleanUp = function() { //清除搜索关键字
    $('#key-word').val('');
    $('#key-word').css('color','#999')
    search.rendererTpl(home.productData.data.product,'',1);
}

search.hideResult = function() { //防止手机输入挡住录入
    $('.no-data').hide();
}



search.searchAuto = function() {
    var keyWord = $('#key-word').val();
    if(keyWord != '' && search.keyWord != keyWord ) {
        search.keyWord = keyWord;
        search.searchResults(keyWord);
        clearInterval(search.searchAutoPlan);
        $("#key-word").focus();
        return false;
    }
    search.searchAutoPlan = setTimeout("search.searchAuto()",1000);
}


search.autoSearch = function() {
    var keyWord = $('#key-word').val();
    if(keyWord == '') {
        if($('#search-page').val() == 1) {
            search.rendererTpl(home.productData.data.product, '', 1);
        }
        return false;
    }
    var re = /[^\u4e00-\u9fa5]/;
    if(re.test(keyWord)) {
        return false;
    } else {
        search.searchResults(keyWord,1);
        return true;
    }
}































/*
 * 选择地区
 */
var select_area = {}
//select_area.city_code = '';
//select_area.city_name = '';
select_area.league_id = 0;
select_area.city_list = new Array();
select_area.city_list_data = '';
select_area.addressData = [];   //收货地址列表
select_area.boxList = null;    //当前所选区域的自提点数据
select_area.zitiData = null;    //当前城市的自提点数据
select_area.selectCityArea = {};   //用户选择的加盟商所在城市区域
select_area.amapStatus = 0;
select_area.cartZitiStatus = 0;   //购物车更换字体点
select_area.paramsData = null;   //保存URL参数
select_area.zitiSwitchType = 1;    //自提点切换到配送

/**
 * 进入城市以及加盟商选择页面
 * @param  {Number} city_code 城市编码
 * @param  {String} city_name 城市名称
 */
select_area.get_city = function(city_code,city_name) {
    if(common.isZitiTest()){
        select_area.cartZitiStatus = 0;
        select_area.getCityList(city_code,city_name);
    }else{
        common.renderTpl("#app_content","selectarea",{});
        common.loaded();
        if(city_name == undefined) {
            select_area.showCityBox();
        } else {
            select_area.change_city(city_code,city_name,0);
        }
    }
}

/**
 * 新版获取城市列表以及分店列表
 * @method select_area.getCityList
 * @methpd {String}
 */
select_area.getCityList = function(city_code,city_name){
    var url = api_host + "/Api/league/get_league_list";
    var openid = user.userBase.bingo_openid;
    if(openid == undefined || openid == null || openid.length == 0){
        return false;
    }
    var data = {
        bingo_access_token: openid
        ,bingo_openid: openid
        ,city_code: city_code
        ,city_list: 1
    }
    $.ajax({type: 'post', url: url, data: data, dataType: 'json', success: function(result){
        if(result.status != 1){
            tipsBox.createAlertBox(result.data);
            return false;
        }
        var data = result.data;
        for(var i = 0, leni = data.city_list.length; i < leni; i++){
            data.city_list[i].league_list = [];
            data.city_list[i].short_name = base.replaceString(data.city_list[i].name,'市','');
            for(var j = 0, lenj = data.league_list.length; j < lenj; j++){
                if(data.city_list[i].code == data.league_list[j].city_code){
                    data.city_list[i].league_list.push(data.league_list[j]);
                }
            }
        }
        data.cityCode = user.userBase.city_code;
        common.renderTpl("#app_content","selectarea_new",data);
        common.loaded();
    }});
}

/**
 * 展开/关闭城市下的区域列表
 * @method select_area.showHideAreaList
 * @param {String} cituCode 城市编码
 */
select_area.showHideAreaList = function(cityCode){
    $('#cityInfoAreaList' + cityCode).toggle();
    if($('#city-code-' + cityCode + ' #cityInfoTop i').hasClass('icon-angle-down')){
        $('#city-code-' + cityCode + ' #cityInfoTop i').removeClass('icon-angle-down').addClass('icon-angle-up');
    }else{
        $('#city-code-' + cityCode + ' #cityInfoTop i').removeClass('icon-angle-up').addClass('icon-angle-down');
    }
}

/**
 * 选择一个区域，显示该区域的配送地址和该区域所属的城市的自提点
 * @method select_area.selectArea
 * @param {Object} paramsData 传递的参数
 */
select_area.send_ziti = function(paramsData){
    var branchId = (paramsData.branchId == undefined || paramsData.branchId == 0) ? "" : paramsData.branchId;
    //排除西区、沙溪，排除西区沙溪的子店
    if(((paramsData.leagueId != 10 && paramsData.leagueId != 13) || ((paramsData.leagueId == 10 || paramsData.leagueId == 13) && branchId != "")) && select_area.cartZitiStatus != 1){
        //除了进西区和沙溪，其他店都是延用旧版直接切换门店
        select_area.set_user_league(paramsData.areaName,paramsData.leagueId,branchId);
        return false;
    }
    //保存URL参数
    select_area.paramsData = paramsData;

    select_area.selectCityArea.branchId = branchId;
    if(select_area.cartZitiStatus == 1){
        //自提点不需要获取送货地址
        select_area.send_zitiData();
        return false;
    }
    //获取该用户的配送地址
    var url = api_host + '/Api/Users/address_list';
    var openid = user.userBase.bingo_openid;
    if(openid == undefined || openid == null || openid.length == 0){
        return false;
    }
    var data = {
        bingo_access_token: openid
        ,bingo_openid: openid
        ,league_id: paramsData.leagueId
        ,branch_id: branchId
    }
    $.ajax({type: 'post', url: url, data: data, dataType: 'json', success: function(result){
        select_area.send_zitiData(result.data);
    }});
}

/**
 * 进入自提/配送选择页面数据处理
 * @method select_area.send_zitiData
 * @param {Object} 收货地址数据
 */
select_area.send_zitiData = function(data){
    var paramsData = select_area.paramsData;
    if(data != undefined){
        user_address.map_model = data.map_model;   //保存用户收货地址地图模式
        select_area.addressData = data.address;
        data.userAddressId = (user.userBase.default_address == undefined) ? 0 : user.userBase.default_address.id;
        data.cityName = paramsData.cityName;
        data.areaName = paramsData.areaName;
    }else{
        data = {address:[]};
    }

    select_area.selectCity = paramsData.cityCode;
    select_area.selectCityArea.cityCode = paramsData.cityCode;
    select_area.selectCityArea.cityName = paramsData.cityName;
    select_area.selectCityArea.areaName = paramsData.areaName;
    select_area.selectCityArea.areaId = paramsData.leagueId;

    var headerData = {};
    headerData.navStatus = paramsData.show_sort;   //优先显示配送还是自提
    headerData.type = paramsData.type;

    common.renderTpl("#app_content","selectarea/send_ziti",data);
    common.renderTpl("#app-header-main","header/header_part2",headerData);
    $('#view_page').css('min-height','0px;');
    $('html,body').scrollTop(0);
    $('#headerPartCityName').html(paramsData.cityName + "<br>" + paramsData.areaName);
    navigation.setHeaderHeight();
    select_area.sendSwitch(paramsData.type);
}

/**
 * 自提点购物车切换配送门店，跳转到城市选择页面
 * @method select_area.goSelectCity
 */
select_area.goSelectCity = function(){
    tipsBox.hideTipsBox();
    select_area.cartZitiStatus = 0;
    select_area.zitiSwitchType = 0;
    window.location.href = "#/selectcity";
}

/**
 * 送货上门与自提切换
 * @method select_area.sendSwitch
 * @param {Number} type
 */
select_area.sendSwitch = function(type){
    type = (select_area.zitiSwitchType == 0) ? select_area.zitiSwitchType : type;
    select_area.zitiSwitchType = 1;
    if(type == 0){
        //送货上门
        if(select_area.cartZitiStatus == 1){
            tipsBox.createConfirmBox('你当前选择的配送方式为自提，切换配送方式需重新选择门店，且因为各门店库存不同，切换时购物车将清空，是否继续？','select_area.goSelectCity','','选择配送');
            return false;
        }
        $('#citySendType0').addClass('current');
        $('#citySendType1').removeClass('current');
        $('#selectareaAddressList').show();
        $('#app-footer').show();
        $('#selectBingoboxWrap').hide();
        $('#app_content').css('padding-bottom','50px');
        if($('#app-footer-main').html() == ""){
            navigation.commonFooterTpl("新增收货地址", "javascript:void(0);","select_area.addressAddEdit()");   //设置底部按钮
        }
        $('#app-header').css('position','fixed');
    }else if(type == 1){
        //自提
        if($('.bingobox-map').data('status') == 0){
            select_area.bingoboxImprotMap();
        }else{
            $('#citySendType0').removeClass('current');
            $('#citySendType1').addClass('current');
            $('#selectareaAddressList').hide();
            $('#app-footer').hide();
            $('#selectBingoboxWrap').show();
            $('#app_content').css('padding-bottom','0');
        }
        $('#app-header').css('position','absolute');
    }
}

/**
 * 自提点地图显示
 * @method select_area.bingoboxImprotMap
 */
select_area.bingoboxImprotMap = function(){
    //加载loading
    common.transparentLoading();

    var url = api_host + '/Api/league/zitilist';
    var openid = user.userBase.bingo_openid;
    if(openid == null || openid == undefined || openid == ""){
        return false;
    }
    var data = {
        bingo_access_token: openid
        ,bingo_openid: openid
        ,city_code: select_area.selectCityArea.cityCode
    }
    $.ajax({type: 'post', url: url, data: data, dataType: 'json', success: function(result){
        if(result.status != 1){
            tipsBox.createAlertBox(result.data);
            return false;
        }
        if(result.data == ""){
            $('.bingobox-map').data('status',"1");
            $('#selectBingoboxWrap').show();
            $('#selectBingobox').hide();
            return false;
        }
        select_area.zitiData = result.data;     //保存当前城市所有自提点数据
        //加载当前城市的自提点信息

        var zitiHtml = "";   //当前第一个分区的所有自提点
        var areaList = result.data.area_list;
        var zitiList = result.data.list;
        var zeroZitiList = [];
        for(var i = 0,len = zitiList.length; i < len; i++){
            if(zitiList[i].area == select_area.paramsData.areaName){
                zitiHtml += '<li id="zitiList-' + zitiList[i].league_id + '"';
                zitiHtml += (zitiList[i].league_id == user.userBase.league_id) ? 'class="current">' : ">";
                zitiHtml += '<div class="bingoziti-item">';
                zitiHtml += '<a href="javascript:select_area.setUserLeague(\'' + zitiList[i].area + '\',\'' + zitiList[i].league_id  +'\',0,0);">';
                zitiHtml += '<span>' + zitiList[i].display_name + '</span>';
                zitiHtml += '</a>';
                zitiHtml += '<a href="javascript:select_area.showZitiView(' + zitiList[i].league_id + ');"></a>';
                zitiHtml += '</div></li>';
                zeroZitiList.push(zitiList[i]);
            }
        }
        if(zitiHtml == ""){
            zitiHtml = '<p id="zitilistNotdata">该区域暂无可用自提点<br>切换其他区域试试</p>';
            $('#bingozitiZitiList').html(zitiHtml);
        }else{
            $('#bingozitiZitiList ul').html(zitiHtml);
        }

        select_area.boxList = zeroZitiList;    //保存地图的自提点;
        var height = config.height - 254;
        $('#selectBingoboxWrap .bingobox-map').height(height);
        $('#amap_map').attr('src', './extend/map/ziti_map.php');
        $('.bingobox-map').data('status',"1");

        //初次加载切换顶部选项卡
        $('#citySendType0').removeClass('current');
        $('#citySendType1').addClass('current');
        $('#selectareaAddressList').hide();
        $('#app-footer').hide();
        $('#selectBingoboxWrap').show();
        $('#app_content').css('padding-bottom','0');
    }});
}

/**
 * 切换自提点分区
 * @method select_area.switchZitiArea
 * @param {Number} areaCode 所选的区域代码
 */
select_area.switchZitiArea = function(areaCode){
    $('#bingbozitiAreaList ul li').each(function(){
        $(this).removeClass('current');
    });
    $('#arreaList-' + areaCode).addClass('current');
    var zitiHtml = "";
    var data = select_area.zitiData.list;
    var zitiData = [];
    for(var i = 0,len = data.length; i < len; i++){
        if(data[i].area_code == areaCode){
            zitiHtml += '<li id="zitiList-' + data[i].league_id + '"';
            zitiHtml += (data[i].league_id == user.userBase.league_id) ? 'class="current">' : ">";
            zitiHtml += '<div class="bingoziti-item">';
            zitiHtml += '<a href="javascript:select_area.setUserLeague(\'' + data[i].area + '\',\'' + data[i].league_id  +'\',0,0);">';
            zitiHtml += '<span>' + data[i].display_name + '</span>';
            zitiHtml += '</a>';
            zitiHtml += '<a href="javascript:select_area.showZitiView(' + data[i].league_id + ');"></a>';
            zitiHtml += '</div></li>';
            zitiData.push(data[i]);
        }
    }
    $('#bingozitiZitiList ul').html(zitiHtml);
    select_area.boxList = zitiData;    //更新当前分区自提点数据
    amap_map.window.boxList = zitiData;    //更新框架内的自提点数据
    amap_map.window.showBingoBox();    //重新绘制地图
}

/**
 * 显示某个自提点的详细信息
 * @method select_area.showZitiView
 * @param {String} id 自提点ID
 */
select_area.showZitiView = function(id){
    $('#page-mark').val('zitiView');
    $('#view_page').hide();
    $('#zitiViewDom').show();
    var data = {};
    for(var i = 0,len = select_area.boxList.length; i < len; i++){
        if(select_area.boxList[i].league_id == id){
            var thisData = select_area.boxList[i];
            thisData.begin_time = (thisData.begin_time === undefined) ? "" : thisData.begin_time;
            thisData.end_time = (thisData.end_time === undefined) ? "" : thisData.end_time;
            data = thisData;
        }
    }
    common.renderTpl("#zitiViewDom","selectarea/ziti_view",data);
    navigation.commonStyle('zitiView');
}

/**
 * 显示收货地址的编辑删除按钮
 * @method select_area.addressDelivery
 */
select_area.addressDelivery = function(){
    if($(".my-address-opera-inner").css('display') == 'block'){
        //隐藏
        $("#sendaddressManagement").text("编辑");
        $(".my-address-opera-inner").hide();
    }else{
        //显示
        $("#sendaddressManagement").text("完成");
        $(".my-address-opera-inner").show();
    }
}

/**
 * 新增/编辑用户的收货地址
 * @method select_area.addressAddEdit
 * @param {String} 为空：新增一个地址/不为空：修改旧地址,数据位置
 */
select_area.addressAddEdit = function(item){
    var dataArea = {};
    dataArea.addr1 = select_area.selectCityArea.cityName + select_area.selectCityArea.areaName;
    if(user_address.map_model == 1){  //加盟商地图模式
        common.renderTpl("#userAddrAdmin","selectarea/address_add",dataArea);
        $('#view_page').hide();
        $('#userAddrAdmin').show();
        $('#page-mark').val('addressAddEidt');
        navigation.commonStyle('addressAddEidt');
        navigation.commonFooterTpl("保存", "javascript:void(0);","select_area.saveAddress()");   //设置底部按钮
        select_area.addressEditData(item);
    }else{
        var url = api_host + "/Api/league/get_delivery_area";
        var openid = user.userBase.bingo_openid;
        if (openid == undefined || openid == null || openid.length == 0) {
            return false;
        }
        var data = {
            bingo_access_token: openid
            ,bingo_openid: openid
            ,league_id: select_area.selectCityArea.areaId
        };
        $.ajax({type: 'post', url: url, data: data, dataType: 'json', success: function (result) {
            dataArea.areaList = result.data;
            common.renderTpl("#userAddrAdmin","selectarea/address_add_old",dataArea);
            $('#view_page').hide();
            $('#userAddrAdmin').show();
            $('#page-mark').val('addressAddEidt');
            navigation.commonStyle('addressAddEidt');
            navigation.commonFooterTpl("保存", "javascript:void(0);","select_area.saveAddress()");   //设置底部按钮
            select_area.addressEditData(item);
        }});
    }
}

/**
 * 修改旧地址带入数据
 * @method select_area.addressEditData
 * @param {Object} 修改地址旧数据
 */
select_area.addressEditData = function(item){
    var addressItem = select_area.addressData[item];
    if (addressItem != "" && addressItem != undefined) {       //修改旧地址
        $("#address_id").val(addressItem.id);
        $("#user_name").val(addressItem.user_name).css('color','#777');
        $("#user_tel").val(addressItem.user_tel).css('color','#777');
        if(user_address.map_model == 1){
            $("#user_addr2").text(addressItem.address).css('color','#6fbfd9');
            $('.select-area-box > div .user-input-address').css('color', '#6fbfd9');
            if(addressItem.baidu_x != "" || addressItem.baidu_x != undefined || addressItem.baidu_x != null){
                $('#coords_x').val(addressItem.baidu_x);
                $('#coords_y').val(addressItem.baidu_y);
            }
            if(addressItem.addr_doorplate != ''){
                $('#doorplate_no').val(addressItem.addr_doorplate).css('color','#777');
            }
        }else{
            if(addressItem.delivery_area_id == '' || addressItem.delivery_area_id == undefined || addressItem.delivery_area_id == null || addressItem.delivery_area_id == 0){
                $("#user_addr2").val("请选择");
            }else{
                $("#admin_my_addr2").val(addressItem.delivery_area_id);
                $("#user_addr2").text(addressItem.area_name);
                $('.select-area-box > div').css('color', '#6fbfd9');
                $('.select-area-box > div span').css('color', '#6fbfd9');
            }
            $("#address_display").html(addressItem.address).css('color','#333');
            $("#address").val(addressItem.address).css('color','#777');
        }
        if(addressItem.tag != '' || addressItem.tag !=null){
            $("#tag").val(addressItem.tag).css('color','#777');
        }
        if(addressItem.tag == '' || addressItem.tag ==null){
            $("#tag").val("家/公司").css('color','#afafaf');
        }
        if (addressItem.is_default == 1) {
            $("#is_default").attr("checked", 'true');
            $('.address-new-add').addClass('current');
        }
    }
}

/**
 * 收货地址加载高德地图
 * @method select_area.importAmapMap
 */
select_area.importAmapMap = function(){
    $('#user_name').blur();
    $('#user_tel').blur();
    $('#address').blur();
    $('#tag').blur();
    $('#is_default').blur();
    $('#app-header').hide();
    $('#app-footer').hide();

    if (map_address.map_is_loaded == 0) {     //地图重设
        common.renderTpl("#importAmapMap","map_address_create",{});

        $("#userAddrAdmin").hide();
        $('.map-loading-wrap').show();
        $('.map-loading-box').show();
        $('#importAmapMap').show();

        //获取加盟商信息
        var openid = user.userBase.bingo_openid;
        var url = api_host + "/Api/league/get_one_user_area";     //获取用户所在区域的加盟商信息
        var data = {
            bingo_access_token: openid
            ,bingo_openid: openid
            ,league_id: select_area.selectCityArea.areaId
            ,branch_id: select_area.selectCityArea.branchId
        };
        $.ajax({type: 'post', url: url, data: data, dataType: 'json', success: function (result) {
            map_address.get_userLeague = result;    //保存加盟商信息
            select_area.amapStatus = 1;
            map_address.create_map_html(select_area.selectCityArea.cityName + "市");    //定位
            map_address.map_is_loaded = 1;
        }});
    } else {
        $('#userAddrAdmin').hide();
        $('#importAmapMap').show();
        if($("#user_addr2").html() != "请选择"){     //已经选了地址
            var addr2 = $('#user_addr2').html();
            var coords_x = $("#coords_x").val();
            var coords_y = $("#coords_y").val();
            if(map_address.map_is_amap == 1){      //高德坐标
                baidu_map.window.panto(coords_x,coords_y);
            }else{
                baidu_map.window.geocoder(addr2);
            }
        }
    }
    $('#app_content').css('padding-bottom','0');
}

/**
 * 保存一个新的收货地址
 * @method select_area.saveAddress
 */
select_area.saveAddress = function(){
    base.checkBtnLock();    //防止重复提交
    var status = user_address.checkAddressData();
    if(status == -1){
        return false;
    }

    var tag_text = $("#tag").val();
    if(tag_text == "家/公司"){
        tag_text = "";
    }
    var url = api_host + "/Api/Users/address_add";
    var openid = user.userBase.bingo_openid;
    if (openid == undefined || openid == null || openid.length == 0) {
        return false;
    }
    var branchId = (select_area.selectCityArea.branchId == "" || select_area.selectCityArea.branchId == 0) ? 'NULL' : select_area.selectCityArea.branchId;
    if(user_address.map_model == 1){      //地图模式
        var data = {
            bingo_access_token: openid
            , bingo_openid: openid
            , user_name: $("#user_name").val()
            , user_tel: $("#user_tel").val()
            , address: $("#user_addr2").html()
            , tag: tag_text
            , is_default: $('input[name="is_default"]:checked').val() == 1 ? 1 : 0
            , baidu_x: $('#coords_x').val()
            , baidu_y: $('#coords_y').val()
            , addr_doorplate: $("#doorplate_no").val()
            , league_id: select_area.selectCityArea.areaId
            , branch_id: branchId
        };
    }else{        //手动填写模式
        var data = {
            bingo_access_token: openid
            , bingo_openid: openid
            , area_name: $("#user_addr2").html()
            , user_name: $("#user_name").val()
            , user_tel: $("#user_tel").val()
            , delivery_area_id: $("#admin_my_addr2").val() //修改地址需要注释
            , address: $("#address").val()
            , tag: tag_text
            , is_default: $('input[name="is_default"]:checked').val() == 1 ? 1 : 0
            , league_id: select_area.selectCityArea.areaId
            , branch_id: branchId
        };
    }
    if ($("#address_id").val() > 0) {
        url = api_host + "/Api/Users/address_edit";
        data.address_id = $("#address_id").val();
        data.branch_id = "";
    }
    $.ajax({type: 'post', url: url, data: data, dataType: 'json', success: function (result) {
        if(result.status != 1){
            tipsBox.createAlertBox(result.data);
            return false;
        }
        if($("#address_id").val() > 0){
            //修改旧地址
            map_address.map_is_loaded = 0;
            select_area.paramsData.type = 0;
            select_area.send_ziti(select_area.paramsData);    //重新获取收货地址
        }else{
            //新增地址
            select_area.selectAddress(result.data.id);
        }

    }});
}

/**
 * 选择配送收货地址，切换分区
 * @method select_area.selectAddress
 * @param {String} id 收货地址id
 */
select_area.selectAddress = function(id){
    var data = select_area.selectCityArea;
    var name = data.areaName;
    var league = data.areaId;
    var branch = data.branchId;
    var addressId = id;
    select_area.setUserLeague(name, league, branch, addressId);
}

/**
 * 询问是否删除该收货地址
 * @method select_area.askDeleteAddress
 * @param {String} id 收货地址id
 */
select_area.askDeleteAddress = function(id){
    tipsBox.createConfirmBox('确定删除该地址吗', 'select_area.sureDeleteAddress', id, '确定');
}

/**
 * 确定删除该收货地址
 * @method select_area.sureDeleteAddress
 * @param {String} id 收货地址id
 */
select_area.sureDeleteAddress = function(id){
    var url = api_host + "/Api/Users/address_delete";
    var openid = user.userBase.bingo_openid;
    if (openid == undefined || openid == null || openid.length == 0) {
        return false;
    }
    var data = {
        bingo_access_token: openid
        , bingo_openid: openid
        , address_id: id
    };
    $.ajax({type: 'post', url: url, data: data, dataType: 'json', success: function (result) {
        if (result.status == 1) {
            tipsBox.hideTipsBox();
            select_area.paramsData.type = 0;
            select_area.send_ziti(select_area.paramsData);    //重新获取收货地址
        }
    }});
}

/**
 * 控制返回自提以及配送页面
 * @method select_area.backSendZiti
 * @param {Number} type 0配送/1自提
 */
select_area.backSendZiti = function(type){
    var headerData = {};
    headerData.navStatus = select_area.paramsData.show_sort;   //优先显示配送还是自提
    headerData.type = select_area.paramsData.type;
    common.renderTpl("#app-header-main","header/header_part2",headerData);
    navigation.setHeaderHeight();
    $('#headerPartCityName').html(select_area.selectCityArea.cityName + "<br>" + select_area.selectCityArea.areaName);
    select_area.sendSwitch(type);   //处理头部菜单
    $('#page-mark').val('sendZiti');
    navigation.commonFooterTpl("新增收货地址", "javascript:void(0);","select_area.addressAddEdit()");   //设置底部按钮
    map_address.map_is_loaded = 0;   //地图重设
    $('#zitiViewDom').html('').hide();
    $('#userAddrAdmin').html('').hide();
    $('#view_page').show();
}

/**
 * (新版)用户更改门店，设置用户新门店
 * @method select_area.setUserLeague
 * @param {String} name 门店名称
 * @param {String} league 门店ID
 * @param {String} branch 门店子店ID
 * @param {String} addresssId 收货地址id
 */
select_area.setUserLeague = function(name, league, branch, addressId) {
    if(select_area.cartZitiStatus == 1){
        select_area.askReplaceZitiTips(name, league, branch, addressId);
        return false;
    }
    var addressId = (addressId == undefined) ? 0 : addressId;
    var url=api_host+"/Api/league/set_user_league";
    var openid=user.userBase.bingo_openid;
    if (openid == undefined || openid == null || openid.length == 0){
        return false;
    }
    var data={
        bingo_access_token:openid
        ,bingo_openid:openid
        ,league_id: league
        ,branch_id: branch
        ,address_id: addressId
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        if(result.status == 1) {
            setCookie('buycar', '', true); //正常商品
            setCookie('buycar_yugou', '', true); //团购商品
            GL_PARTNANE = name;
            user.userBase.short_name = name;
            user.userBase.league_id = league;
            user.userBase.branch_id = branch;
            cart.user_receive_time = '';
            _user_has_league = 1;
            if(_come_from != '') { //用户来自外部
                window.location.href = _come_from;
                return false;
            }

            if(common.getCookie('come_from') != '' && common.getCookie('come_from') != null ) {
                window.location.href = common.getCookie('come_from');
                return false;
            }

            if(_user_come_from == '') { //用户来自那里
                window.location.href = config.pathUrl +'?part=1';
            } else {
                window.location.href = config.pathUrl +'home.php'+_user_come_from;
            }
        } else {
            window.location.href = config.pathUrl;
        }
    }});
}

/**
 * 自提点更换到自提点(购物车按钮，商城首页顶部中间按钮)
 * @method select_area.replaceZiti
 * @param {Number} type 0配送/1自提
 */
select_area.replaceZiti = function(type){
    select_area.cartZitiStatus = (type == 1) ? 1 : 0;   //标注选择自提点的提示
    var branchId = (user.userBase.branch_id == "") ? 0 : user.userBase.branch_id;
    var cityName = base.replaceString(select_area.city_list[user.userBase.city_code],'市','');
    var show_sort = (navigation.menu.city_league.show_sort != 0 && navigation.menu.city_league.show_sort != 1) ? 0 : navigation.menu.city_league.show_sort;
    // console.log("#/send_ziti/" + user.userBase.league_id + "/" + user.userBase.city_code + "/" + branchId + "/" + cityName + "/" + user.userBase.area_name + "/" + type + "/" + show_sort);
    // return false;
    window.location.href = "#/send_ziti/" + user.userBase.league_id + "/" + user.userBase.city_code + "/" + branchId + "/" + cityName + "/" + user.userBase.area_name + "/" + type + "/" + show_sort;
}

/**
 * 询问是否切换自提点，会清空购物车
 * @method select_area.replaceZitiTips
 */
select_area.askReplaceZitiTips = function(name, league, branch, addressId){
    var params = name + ',' + league + ',' + branch + ',' + addressId;
    tipsBox.createConfirmBox('由于各门店水果品类各有不同，为确保您的订单有效，更改自提地址会清空您的购物车，点击确定按钮确定更改', 'select_area.sureReplaceZitiTips', params, '确定');
}

/**
 * 确定切换自提点
 * @method select_area.sureReplaceZitiTips
 */
select_area.sureReplaceZitiTips = function(name, league, branch, addressId){
    select_area.cartZitiStatus = 0;
    select_area.setUserLeague(name, league, branch, addressId);
}

/**
 * 设置地区选项为正方形
 * @method select_area.resize
 */
select_area.resize = function() {
    var width = $(window).width();
    var height = width / 4;
    $('.select-area-main ul li').css('width',height + 'px');
    $('.select-area-main ul li').css('height',height + 'px');
}

select_area.change_city = function(city_code, city_name,city_box) {
    $('#city-code-box li').removeClass('current');
    $('#city-code-'+city_code).addClass('current');
    if (city_name!=undefined && city_name!=0) {
        $('#user-city').html(city_name);
    }
    var url = api_host+"/Api/league/get_league_list";
    var openid = user.userBase.bingo_openid;
    if (openid == undefined || openid == null || openid.length == 0){
        return false;
    }
    var data={ "bingo_access_token" : openid,"bingo_openid" : openid,'city_code': city_code };
    if (select_area.league_id!=0 && city_code==0 && city_name==0 && city_box==0){
        data.league_id=select_area.league_id;
    }
    $.ajax({type:'post',url:url,data:data,dataType: 'json', async:false, success:function(result){
        var itemStr = '';
        var league_list = result.data.league_list;
        var short_name = "";
        for (var k in league_list) {
            short_name = league_list[k]['short_name'];
             if(league_list[k]['short_name'].length  >= 4) {
                short_name = "<span style='display:block; line-height: 100%; border-width: 0; padding:0; margin-bottom: -25%;'>" + league_list[k]['short_name'].substring(0,2)+'<br/>'+ league_list[k]['short_name'].substring(2)+"</span>";
             }

             league_list[k]['branch_id'] = league_list[k]['branch_id'] == undefined ? 0 : league_list[k]['branch_id'];
             itemStr += '<li>';
             itemStr += '<a href="javascript:void(0);"';
             itemStr += (league_list[k]['select'] == 1) ? ' class="current" ' : '';
             itemStr += 'title="'+league_list[k]['short_name']+'" onclick="select_area.set_user_league(\''+league_list[k]['short_name']+'\',\''+league_list[k]['league_id']+'\',\''+league_list[k]['branch_id']+'\')"><span>'+short_name+'</span></a>';
             itemStr += (league_list[k]['is_new'] == 1) ? '<em>新</em>' : '';
             itemStr += '</li>';
        }
        $('.no-find-city').hide();
        $('#city-part').html(itemStr);

        if(common.isZitiTest()) {
            result.data.city.name = base.replaceString(result.data.city.name,'市','');
            common.renderTpl('#city-select-box','selectarea/change_city',result.data.city);
            $('#city-select-box').show();
        }

        // select_area.resize();
        if(city_box == 1) {
            select_area.showCityBox();
        }
    }});
}

select_area.set_user_position_city = function() { //设置用户所在地区
    $("#area_short_name").text(user.userBase.short_name);
    if(user.userBase.city_code == '') {
         $("#area_short_name").attr('href','./home.php#/selectcity');
    } else {
        $("#area_short_name").attr('href','./home.php#/selectcity/'+select_area.city_list[user.userBase.city_code]+"/1");
    }
}

select_area.back = function() {
    base.recoverPenetration();
    config.setBackBtn();
}


select_area.show_city_part = function(city_name) {
    if(select_area.city_list.length <= 0) {
        var url = api_host+"/Api/league/get_city_list";
        var openid = user.userBase.bingo_openid;
        if (openid == undefined || openid == null || openid.length == 0){
            return false;
        }
        var data = { "bingo_access_token" : openid,"bingo_openid" : openid };
        $.ajax({type:'post',url:url,data:data,dataType: 'json', async:false, success:function(result){
            if(result.status == 1) {
                for(var k in result.data) {
                    select_area.city_list[result.data[k]['code']] = result.data[k]['name'];
                }
                select_area.chioce_show_city_method(city_name);

            } else {
                window.location.href="./home.php#/selectcity";
            }
        }});
    } else {
        select_area.chioce_show_city_method(city_name);
    }
}

select_area.chioce_show_city_method = function(city_name) { //跳转到指定模式的选择地址页面
    var code = common.get_array_key(select_area.city_list,city_name);
    if(code == '') {
        window.location.href="./home.php#/selectcity";
        return false;
    }
    select_area.get_city(code,city_name);
}


select_area.get_user_auto_league = function() { //根据经纬度自动获取用户所属加盟商
    var location_type = "baidu";
    var url = api_host+"/Api/league/get_user_auto_league";
    var openid = user.userBase.bingo_openid;
    if (openid == undefined || openid == null || openid.length == 0){
        return false;
    }

    var data = {
        bingo_access_token:user.openid
        ,bingo_openid:user.openid
        ,longitude:longitude
        ,latitude:latitude
        ,set_user_league: 0
        ,type: location_type
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json', async:false, success:function(result){}});
}

select_area.set_user_league = function(name, league, branch) { //用户改变自身的地区
    var url=api_host+"/Api/league/set_user_league";
    var openid=user.userBase.bingo_openid;
    if (openid==undefined || openid==null || openid.length==0){
        return false;
    }
    var data={
        bingo_access_token:openid
        ,bingo_openid:openid
        ,league_id: league
        ,branch_id: branch
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        if(result.status == 1) {
            setCookie('buycar', '', true); //正常商品
            setCookie('buycar_yugou', '', true); //团购商品
            GL_PARTNANE = name;
            user.userBase.short_name = name;
            user.userBase.league_id = league;
            user.userBase.branch_id = branch;
            cart.user_receive_time = '';
            _user_has_league = 1;
            if(_come_from != '') { //用户来自外部
                window.location.href = _come_from;
                return false;
            }

            if(common.getCookie('come_from') != '' && common.getCookie('come_from') != null ) {
                window.location.href = common.getCookie('come_from');
                return false;
            }

            if(_user_come_from == '') { //用户来自那里
                window.location.href = config.pathUrl +'?part=1';
            } else {
                window.location.href = config.pathUrl +'home.php'+_user_come_from;
            }
        } else {
            window.location.href = config.pathUrl;
        }
    }});
}


select_area.showCityBox = function() {
    if(select_area.city_list_data == '') {
        var url=api_host+"/Api/league/get_city_list";
        var data = { bingo_access_token:user.userBase.bingo_openid};
        $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
            if(result.status == 1) {
                for(var k in result.data) {
                    result.data[k].short_name = result.data[k].name.replace('市','');
                }
                select_area.city_list_data = result;
                common.renderTpl('#city-list-box','city_list',select_area.city_list_data);
            }
        }});
    } else {
        common.renderTpl('#city-list-box','city_list',select_area.city_list_data);
    }
    base.preventPenetration();     //禁止底层滚动
    var windowHeight = $(window).height();
    var height = $('#app-header').height();
    var selectBox = $('#select-city-box').val();
    $('#city-list-box').css({'top':height,'height': parseInt(windowHeight - height) + 'px'});
    if(selectBox == 0) {
        $('#select-city-box').val(1);
        $("#city-list-box").show();
        if(_is_app != 1) {
            $('#app-header').css('position', 'fixed');
        }
        $('#change-city-icon').addClass('icon-angle-up');
        $('#change-city-icon').removeClass('icon-angle-down');
        config.setPageMinHeight();
    } else {
        $('#select-city-box').val(0);
        $("#city-list-box").hide();

        base.recoverPenetration();   //恢复底层滚动

        if(_is_app != 1) {
            $('#app-header').css('position', 'inherit');
        }
        $('#change-city-icon').addClass('icon-angle-down');
        $('#change-city-icon').removeClass('icon-angle-up');
    }
}

select_area.removeAnimete = function(status) {
    $('.select-city-item').removeClass('selected-city-animate-big');
    $('.select-city-item').removeClass('selected-city-animate-small');
    if(status == 0) {
        $('.select-city-item').hide();
        $('.select-city-box-mask').hide();
    }
}

select_area.city_info = function(code) { //城市信息
    var url=api_host+"/Api/league/get_city_league_list";
    var openid=user.userBase.bingo_openid;
    if (openid==undefined || openid==null || openid.length==0){
        return false;
    }
    var data={
        bingo_access_token:openid
        ,city_code:code
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        if(result.status == 1) {
            var html = template('city_info',result);
            $("#app_content").html(html);
            $(".city_table_parent td.first-children").each(function(){
                var fontHeight = $(this).find('em').height();
                var parentHeight = $(this).find('span').height();
                var finalTop = (parseInt(parentHeight) -  parseInt(fontHeight) ) / 2;
                $(this).find('em').css('top',finalTop+"px");
            });
            $('.footer-table tr td.left div').hide();
            $('.footer-table tr td.right div').hide();
            common.loaded();
        } else {
            tipsBox.createAlertBox(result.data);
        }
    }});
}

select_area.show_part_map = function(map,status) {
    if(status == 1) {
        $('#city_info_map_path').attr('src',map);
        $('#city_info_mask').show();
        tipsBox.tipsBoxCenter('#city_info_mask div');
    } else {
        $('#city_info_mask').hide();
    }
}

select_area.current_position = function() { //地区信息
    var url=api_host+"/Api/league/get_one_user_area";
    var openid=user.userBase.bingo_openid;
    if (openid==undefined || openid==null || openid.length==0){
        return false;
    }
    var data={
        bingo_access_token:openid
        ,bingo_openid:openid
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        if(result.status == 1) {
            result.data.city_name = select_area.city_list[result.data['city_code']];
            var html = template('current_position',result);
            $("#app_content").html(html);

            $('.footer-table tr td.left div').hide();
            $('.footer-table tr td.right div').hide();
            common.loaded();
        } else {
            tipsBox.createAlertBox(result.data);
        }
    }});
}
var share_app = {};
share_app.isShare = 0;

/**
 * App分享数据初始化
 * @param {Stirng} title 标题
 * @param {String} describe 内容
 * @param {String} images 图片
 * @param {String} url 地址
 */
share_app.init = function(title, describe, images, url) {
    share_app.weixin =  { 'title': title, 'description': describe, 'thumb': images, 'webpageUrl': url };
    share_app.QQ = { 'title': title, 'description': describe, 'imageUrl': images, 'url': url, 'appName': '缤果水果' };
    share_app.qzone = { 'title': title, 'description': describe,'imageUrl': [images],'url':url };
    share_app.weibo = { 'title': title, 'description': describe,'images': images,'url':url };
}

/**
 * 分享按钮
 * @method share_app.shareBtn
 * @param {String} type 类型
 */
share_app.shareBtn = function(type) {
    //return false;
    switch(type) {
        case 'weixin':
        case 'friends':
            Wechat.isInstalled(function (installed) {
                if(installed) {
                    share_app.shareEvent(type);
                } else {
                    tipsBox.createAlertBox('你没有安装微信哦');
                }
            }, function (reason) {
                tipsBox.createAlertBox(reason);
            });
            break;
        case 'QQ':
        case 'qzone':
            YCQQ.checkClientInstalled(function(){
                share_app.shareEvent(type);
            },function(){
                tipsBox.createAlertBox('你没有安装QQ哦');
            });
            break;

        case 'weibo':
            var weibo = share_app.weibo;
            var type = 'com.sina.weibo';
            if(config.isAppleDevice == 1) {
                type = 'com.apple.social.sinaweibo';
            }
            window.plugins.socialsharing.canShareVia(type, weibo.title, weibo.description, weibo.images, weibo.url, function(){
                share_app.shareEvent('weibo');
            },function(){
                tipsBox.createAlertBox('你没有安装微博哦');
            });
            break;
    }
}

/**
 * 分享事件触发
 * @method share_app.shareEvent
 * @param {String} type 类型
 */
share_app.shareEvent = function(type) {
    switch(type) {
        case 'weixin':
            var weixin = share_app.weixin;
            share_app.appWeixinShare(0, weixin.title, weixin.description, 'mediaTagName', weixin.thumb, weixin.webpageUrl, share_app.success, share_app.failed);
            break;
        case 'friends':
            var weixin = share_app.weixin;
            share_app.appWeixinShare(1, weixin.title, weixin.description, 'mediaTagName', weixin.thumb, weixin.webpageUrl, share_app.success, share_app.failed);
            break;
        case 'QQ':
            YCQQ.shareToQQ(share_app.success, share_app.failed, share_app.QQ);
            break;
        case 'qzone':
            YCQQ.shareToQzone(share_app.success, share_app.failed, share_app.qzone);
            break;
        case 'weibo':
            var weibo = share_app.weibo;
            var type = 'com.sina.weibo';
            if(config.isAppleDevice == 1) {
                type = 'com.apple.social.sinaweibo';
            }
            window.plugins.socialsharing.shareVia(type, weibo.title, weibo.description, weibo.images, weibo.url, share_app.success, share_app.failed);
            break;
    }
}

/**
 * App 微信分享
 * @method share_app.appWeixinShare
 * @param {Number} scene 标识,0: 好友 1: 朋友圈
 * @param {String} title 标题
 * @param {String} description 描述
 * @param {String} mediaTagName
 * @param {String} thumb 图片
 * @param {String} webpageUrl 网址
 * @param {Function} success 成功回调函数
 * @param {Function} failed 失败回调函数
 */
share_app.appWeixinShare = function (scene, title, description, mediaTagName, thumb, webpageUrl, success, failed) {
    //scene 0: 好友 1: 朋友圈
    Wechat.share({
        message: {
            title: title,
            description: description,
            mediaTagName: mediaTagName,
            thumb: thumb,
            media: {
                type: Wechat.Type.WEBPAGE,   // webpage
                webpageUrl: webpageUrl
            }
        },
        scene: scene   // share to Timeline
    }, function () {
        success();
    }, function (reason) {
        failed();
    });
};

/**
 * App分享操作
 * @method share_app.operate
 * @param {Stirng} status 状态
 * @param {Stirng} title 标题
 * @param {String} describe 内容
 * @param {String} images 图片
 * @param {String} url 地址
 */
share_app.operate = function(status, title, describe, images, url) {
   // return false;
    if(status != 1) {
        return false;
    }
    var page = $('#page-mark').val();
    switch (page) {
        case 'product-info':
            if(share_app.isShare == 0) {
                $('#share-app-btn').css('display', 'block');
            } else {
                $('#return-btn').hide();
                share_app.download();
                navigation.setHeaderHeight();
            }
            break;
        case 'share_order':
            if(share_app.isShare == 1) {
                $('#app-header').show();
                share_app.download();
                navigation.setHeaderHeight();
            }
            $('.common-footer a').attr('onclick','tipsBox.createShareAppBox()');
            break;
    }
    share_app.isShare = 0;
    share_app.init(title, describe, images, url);
}

/**
 * 分享成功
 * @method share_app.success
 */
share_app.success = function() {
    var page = $('#page-mark').val();
    switch (page) {
        case 'share':
            shareOrder.score_add();
            break;
        case 'share_order':
            shareOrder.score_add();
            break;
    }
    share_app.tips('分享成功','icon-ok-sign');
}

/**
 * 分享失败
 * @method share_app.failed
 */
share_app.failed = function() {
    share_app.tips('分享失败','icon-remove-sign');
}

/**
 * 分享提示
 * @method share_app.tips
 * @param {String} className
 * @param {String} tips
 */
share_app.tips = function(tips,className) {
    var html = '<div id="share-app-tips" class="tc"><dl><dt class="'+className+'"></dt><dd>'+tips+'</dd></dl></div>';
    $(tipsBox.container).css('background','transparent');
    $(tipsBox.container).html(html);
    tipsBox.tipsBoxCenter('#tips-box > div');
    $(tipsBox.container).show();
    $(tipsBox.container).addClass('share-app-anima');
    setTimeout(function() {
        $(tipsBox.container).removeAttr('style');
        $(tipsBox.container).removeAttr('class');
    },1500);
}

/**
 * 下载
 * @method share_app.download
 */
share_app.download = function() {
    var url = 'http://a.app.qq.com/o/simple.jsp?pkgname=com.bingofresh.mobile.user';
    common.renderTpl('#app-header-main','header/header_share',{'url' : url});
}



var shareOrder = {};
shareOrder.jumbUrl = '';
shareOrder.myselfUrl = '';
shareOrder.shareStatus = 0;
shareOrder.orderId = 0;
shareOrder.user_share_order = 0;
shareOrder.shareReturnStatus = 0;
shareOrder.showShare = function(status) {
    if(status == 0) { 
        $('.share-stup').hide();
    } else {
        $('.share-stup').show();
    }
}

shareOrder.goOnUserCommitShare = function() {
    tipsBox.hideTipsBox();
    $('#is_double_share').val(0);
    shareOrder.userCommitShare();
}

shareOrder.userCommitShare = function() { //用户提交分享信息
    var img_url = '';
    var comment = $('#comment').val();
    var orderno = $('#upload_orderno').val();
    var fristImg = $('.img-1').find('img').attr('src') != undefined ? $('.img-1').find('img').attr('src').replace('..','') : '';
    
    shareOrder.jumbUrl = '';
    $(".share-img-box li").each(function(index){
        if(!$(this).hasClass('add')){
            img_url += $(this).find('img').attr('src').replace('..','')+",";
        }
    });
    if(img_url == '') {
        alertBox('.alert-box','您还没有添加商品图片哟~添加图片可让描述更直观！');
        return false;
    }
    if(uploadImg.upComplete == 0) {
        alertBox('.alert-box','图片正在上传中...');
        return false;
    }
    if(comment == '') {
        alertBox('.alert-box','请描述一下你所收到的商品，分享后可以获得积分奖励哟！');
        return false;
    }
    
    if($('#is_double_share').val() === '1') {
        tipsBox.createConfirmBox($('#double_tip').val(),'shareOrder.goOnUserCommitShare','1','继续晒单');
        $('.confirm-wrap table tr td:first-child a').html('先不晒了');
        return false;
    }


    $('#share-commit').hide();
    $('#share-commiting').show();
    var order_id = $('#upload_order_id').val();
    var url = api_host+"/Api/AfterSale/share";
    var openid = user.userBase.bingo_openid;
    if (openid==undefined || openid==null || openid.length==0){
        return false;
    }
    var data={
        bingo_access_token:openid
        ,bingo_openid:openid
        ,order_id:order_id
        ,comment:comment
        ,img_url:img_url
    };
    var ajaxTimeout = $.ajax({type:'post',url:url,timeout: 3000,data:data,dataType: 'json',success:function(result){
        if(result.status == "1" || result.status == '-06007') {
            shareOrder.jumbUrl = 'http://'+window.location.host+'/go.php?go=shareorder&id='+orderno+'&type=otherself';
            shareOrder.myselfUrl = 'http://'+window.location.host+'/go.php?go=shareorder&id='+orderno+'&type=myself';

            if(_is_app == 1) {
                shareOrder.myselfUrl = '#/shareorder/'+orderno+'/myself';
                tipsBox.createShareAppBox();
            } else {
                shareOrder.showShare(1);
            }

            var title = "已经第"+$('#all_times').val()+"次在缤果购买了，真的离不开了…";
            var images = fristImg;
            var describe = comment;
            var url = shareOrder.jumbUrl;
            var app_shere = config.appShareUrl +'?page=share_order&id='+order_id;

            share_info = { "title": title, "img_url": images, "content": describe, "url": url };
            share_app.operate(_is_app,title, describe, images, app_shere);

            $('#share_jump').attr('href',shareOrder.myselfUrl);
            shareOrder.shareStatus = 1;
            shareOrder.user_share_order = 1;
        } else {
            tipsBox.createAlertBox(result.data)
            $('#share-commit').show();
            $('#share-commiting').hide();
        }
    }, error: function(XMLHttpRequest,status){ //超时处理
        $('#share-commit').show();
        $('#share-commiting').hide();
        ajaxTimeout.abort();
        if(status == 'timeout') {
           tipsBox.createAlertBox('糟糕，你的网络有问题，请求超时啦');
　　　　 }
        if(status == 'abort') {
            tipsBox.createAlertBox('糟糕，你的网络有问题，链接中断啦');
        }
    }});

    
}

/**
 * 获得订单分享信息
 * @method shareOrder.shareSetInfo
 * @param {String} orderid 订单id
 * @param {Number} type 类型
 */
shareOrder.shareSetInfo = function(orderid,type) {
    shareOrder.jumbUrl = '';
    shareOrder.shareReturnStatus = 1;
    shareOrder.operaShareSetInfo(orderid, type);
}

/**
 * 操作订单分享信息
 * @method shareOrder.operaShareSetInfo
 * @param {String} orderid 订单id
 * @param {Number} type 类型
 */
shareOrder.operaShareSetInfo = function(orderid,type) {
    var url = api_host+"/Api/AfterSale/get_share_info";
    var openid = user.userBase.bingo_openid;
    var data = { bingo_access_token: openid, bingo_openid: openid, order_id: orderid };
    var enter = type;
    if(enter == 'aftersale') {
        type = 'myself';
    }

    $.ajax({type: 'post', url: url, data: data, dataType: 'json', success: function(result) {

        if(result.data.is_share === '1') {
            if(shareOrder.shareReturnStatus == 1 && history.length != 1) {
                shareOrder.shareReturnStatus = 0;
                window.history.back(-2);
            } else {
                window.location.href = '#/shareorder/' + orderid + '/myself';
            }
            return false;
        }

        result.total = 0;
        result.orderid = orderid;
        for (var i = 0; i < result.data.product.length; i++) {
            if(result.data.product[i].id != 0 ) {
                result.total++;
            }
        }

        common.renderTpl("#app_content",'share/share',result);
        if(enter == 'aftersale') {
            $('#share-return').attr('href','javascript:history.back()');
        }

        $('#file-input').val('');
        uploadImg.upComplete = 1;
        uploadImg.folder = 'Appraise';

        shareOrder.shareStatus = 1;
        shareOrder.orderId = orderid;
        navigation.commonFooterTpl('提交并晒单','','shareOrder.userCommitShare()');
        common.loaded(1);
    }});
}

shareOrder.shareFruitShow = function() {
   var show = $('#shareShow').val();
   if(show == 1) {
       $('.share-order-list h2 span').removeClass('up');
       $('.share-order-list ul').hide();
       $('#shareShow').val(0);
   } else {
       $('.share-order-list h2 span').addClass('up');
       $('.share-order-list ul').show();
       $('#shareShow').val(1);
   }

}

shareOrder.shareOrderBtn = function(orderid) { //分晒订单按钮
    var url = api_host+"/Api/AfterSale/get_order_share";
    var data={
        bingo_secret:'fb92390dd7c59c3fcb4fcce4801aadecb79f2e4a'
        ,order_id:orderid
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        if(result.data == '') {
             window.location.href = '#/shareset/'+orderid;
        } else {
             window.location.href = '#/shareorder/'+orderid+'/myself';
        }
    }});
}

shareOrder.isShareOrder = function(orderid, type) {
    var url = api_host+"/Api/AfterSale/get_order_share";
    var data={
        bingo_secret:'fb92390dd7c59c3fcb4fcce4801aadecb79f2e4a'
        ,order_id:orderid
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        if(result.data != '') {
             window.location.href = '#/shareorder/'+orderid+'/'+type;
        } else {
            shareOrder.operaShareSetInfo(orderid, type);
        }
    }});
}

shareOrder.showBigImg = function(src, status, index){ //查看大图
    if(status == 1) {
        $('.share-big-img').show();
        $('#share-pre').show();
        $('#share-next').show();
        $('.share-big-img img').attr('src',src);
        $('.share-big-img img').addClass('slide-slate-btn');
        tipsBoxCenter('.share-big-img img');
    } else {
        $('.share-big-img').hide();
        $('#share-pre').hide();
        $('#share-next').hide();
    }
    $('#share-index').val(index);
}

/**
 * 用户分享订单信息
 * @method shareOrder.userShareInfo
 * @param {String} orderid 订单
 * @param {String} user 用户,myself 分享者自己, other 其它人
 */
shareOrder.userShareInfo = function(orderid,user) {
    var url = api_host + "/Api/AfterSale/get_order_share";
    var data = { bingo_secret:'fb92390dd7c59c3fcb4fcce4801aadecb79f2e4a', order_id: orderid };
    var enter = user;
    if(enter == 'aftersale') {
        user = 'myself';
    }
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        result.i = 0;
        result.user = user;
        result.data.img_url = result.data.img_url.split(",");
        common.renderTpl("#app_content",'share/share_order',result);

        shareOrder.shareStatus = 1;
        shareOrder.orderId = orderid;
        shareOrder.user_share_order = 1;

        if(user != 'myself') {
            $('#app-header').hide();
        }
        common.loaded(1);
        if(user != 'myself') {
            shareOrder.userBuyFruit(result);
            navigation.commonFooterTpl('去缤果商城','#/home','','share-footer bd-style');
            $('.share-footer a').removeClass('style-color');
            $('.share-footer a').addClass('bd-style');
            $('.share-footer a').addClass('bd-color');
            $('.share-footer a').addClass('ft-color');
        } else {
            $('.share-set-wrap').attr('style','margin-top: 13px;');
            navigation.simpleStyle('晒单');
            navigation.commonFooterTpl('分享到朋友圈','','shareOrder.showShare(1)');
        }

        var title = "已经第"+result.data.all_times+"次在缤果购买了，真的离不开了…";
        var images = result.data.img_url[0];
        var describe = result.data.comment;
        var url = 'http://'+window.location.host+'/go.php?go=shareorder&id='+orderid+'&type=otherself';
        share_info = { "title": title, "img_url": images, "content": describe, "url": url };

        var app_shere = config.appShareUrl +'?page=share_order&id='+orderid;
        share_app.operate(_is_app,title, describe, images, app_shere);
    }});
}

/**
 * 订单用户购买的水果
 * @method shareOrder.userBuyFruit
 * @param result
 */
shareOrder.userBuyFruit = function(result) {
    result.total = 0;
    result.save = 0;
    var save = 0;
    for (var i = 0;i< result.data.product.length;i++) {
        if(result.data.product[i].id != 0 ) {
            save =  parseFloat(result.data.product[i]['shichangjia']) - parseFloat(result.data.product[i]['price']);
            save = save > 0 ? save : 0;
            result.save += save;
            result.total++;
        }
    }
    common.renderTpl(".share-order-list",'share/share_use_buy',result);
}
/*晒单分享修改旧代码，确定不使用后可删除 by feng*/
// shareOrder.next = function() {
//     var index = $('#share-index').val();
//     var max = $('#share-max').val();
//     index = parseInt(index) + 1;
//     max = parseInt(max) - 1;
//     if(index > max) {
//         index = 0;
//     }
//     var src =  $('#share-order-img').children().eq(index).find('img').attr('src');
//     var style = $('.share-big-img img').attr('style');
//     $('.share-big-img').html('<img src="" width="100%" style="'+style+'"/>');
//     $('.share-big-img img').attr('src',src);
//     $('.share-big-img img').addClass('slide-right-btn');
//     $('#share-index').val(index);
// }
// shareOrder.pre = function() {
//     var index = $('#share-index').val();
//     index = parseInt(index) - 1;
//     if(index < 0 ) {
//         var max = $('#share-max').val();
//         index = parseInt(max) - 1;
//     }
//     var src =  $('#share-order-img').children().eq(index).find('img').attr('src');
//     var style = $('.share-big-img img').attr('style');
//     $('.share-big-img').html('<img src="" width="100%" style="'+style+'"/>');
//     $('.share-big-img img').attr('src',src);
//     $('.share-big-img img').addClass('slide-left-btn');
//     $('#share-index').val(index);
// }
/*by feng in 20151124 total*31*/
shareOrder.next = function() {
    var first_index = $("#share-order-img").children().first().attr('id').replace('share-order-img-','');   //第一张
    var index = $('#share-index').val();
    var max = $('#share-max').val();
    index = parseInt(index) + 1;
    max = parseInt(max) - 1;
    if(index > max) {
        index = parseInt(first_index);
    }
    var src =  $('#share-order-img').children('#share-order-img-'+index).find('img').attr('src');
    var style = $('.share-big-img img').attr('style');
    $('.share-big-img').html('<img src="" width="100%" style="'+style+'"/>');
    $('.share-big-img img').attr('src',src);
    $('.share-big-img img').addClass('slide-right-btn');
    $('#share-index').val(index);
}
shareOrder.pre = function() {
    var first_index = $("#share-order-img").children().first().attr('id').replace('share-order-img-','');    //第一张
    var last_index = $("#share-order-img").children().last().attr('id').replace('share-order-img-','');    //最后一张
    var index = $('#share-index').val();
    index = parseInt(index) - 1;
    if(index < parseInt(first_index)) {
        index = parseInt(last_index);
    }
    var src =  $('#share-order-img').children('#share-order-img-'+index).find('img').attr('src');
    var style = $('.share-big-img img').attr('style');
    $('.share-big-img').html('<img src="" width="100%" style="'+style+'"/>');
    $('.share-big-img img').attr('src',src);
    $('.share-big-img img').addClass('slide-left-btn');
    $('#share-index').val(index);
}

shareOrder.score_add = function() {
    if(shareOrder.user_share_order != 1 ) {
        return false;
    }
    if(shareOrder.shareStatus == 0) {
        return false;
    }
    shareOrder.showShare(0);
    shareOrder.shareStatus = 0;
    var url = api_host+"/Api/Score/score_add";
    var openid = user.userBase.bingo_openid;
    if (openid==undefined || openid==null || openid.length==0){
        return false;
    }
    var data={
        bingo_access_token:openid
        ,bingo_openid:openid
        ,bingo_appid:config.appid
        ,rule_id:'share_order'
        ,status:'1'
        ,relation_id:shareOrder.orderId
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        if(shareOrder.jumbUrl != '') {
            window.location.href = shareOrder.myselfUrl;
        }
    }});
}

var uploadImg = {};
uploadImg.base64_img = '';
uploadImg.folder = '';
uploadImg.fileName = 'file-input'; //上传文件名
uploadImg.uploadPath = 'upload.php?act=img_upload&folder='+uploadImg.folder+'&orderno=1&num=1'; //上传图片生成路径
uploadImg.progressName = 'progress'; //上传图片进度名id
uploadImg.upComplete = 1;

/**
 * 新增图片
 * @returns {boolean}
 */
uploadImg.add = function() {
    if(uploadImg.upComplete == 0){
        alertBox('.alert-box','图片正在上传中...');
        return false;
    }
    var orderno = $('#upload_orderno').val();
    var num = parseInt($('#upload_total').val()) + 1;
    $('#upload_status').val('add');
    uploadImg.uploadPath = 'upload.php?act=img_upload&folder='+uploadImg.folder+'&orderno='+orderno+'&num='+num;
    $('#photo-tips').hide();
}
uploadImg.insert = function(num) {       //更换
    if(uploadImg.upComplete == 0){
        alertBox('.alert-box','图片正在上传中...');
        return false;
    }
    var orderno = $('#upload_orderno').val();
    $('#upload_num').val(num);
    $('#upload_status').val('insert');
    uploadImg.uploadPath = 'upload.php?act=img_upload&folder='+uploadImg.folder+'&orderno='+orderno+'&num='+num;
}
//uploadImg.fileSelected = function(dom_name,width,quality) {
/*晒单分享修改旧代码，确定不使用后可删除 by feng*/
// uploadImg.fileSelected = function() {
//     if(uploadImg.upComplete == 0) {
//         alertBox('.alert-box','图片正在上传中...');
//         return false;
//     }
//     uploadImg.upComplete = 0;
//     var file = document.getElementById(uploadImg.fileName).files[0];
//     var URL = window.URL || webkitURL;
//     var blob = URL.createObjectURL(file);
//     uploadImg._create(blob,"img_area",300,1);
    
//     var status = $('#upload_status').val();
//     if(status == 'add') {
//         var num = parseInt($('#upload_total').val()) + 1;
//         var item = '<li class="img-'+num+'"><img src="./ui/images/share_add_btn.png?v=1" width="100%" height="auto" /><label for="file-input" onclick="uploadImg.insert('+num+')"><span class="load-wrap"><em></em></span></label></li>';
//         $('.share-img-box li.add').before(item);
//         $('.img-'+num).find('label').addClass('load');
//     }
//     if(status == 'insert') {
//          var num = $('#upload_num').val();
//         $('.img-'+num).find('label').addClass('load');
//     }
// }

/*by feng in 20151124 total*19*/
uploadImg.fileSelected = function() {
    if(uploadImg.upComplete == 0) {
        alertBox('.alert-box','图片正在上传中...');
        return false;
    }

    uploadImg.upComplete = 0;
    $('.share-img-box').find('label').attr('for','');
    var file = document.getElementById(uploadImg.fileName).files[0];
    var URL = window.URL || webkitURL;
    var blob = URL.createObjectURL(file);
    uploadImg._create(blob,"img_area",300,1);
    
    var status = $('#upload_status').val();
    if(status == 'add') {
        var num = parseInt($('#upload_total').val()) + 1;
        var item = '<li class="share-img img-'+num+'"><img src="./ui/images/share_add_btn.png?v=2" width="100%" height="auto" /><label onclick="uploadImg.insert('+num+')"><span class="load-wrap"><em></em></span></label><i class="icon-remove-sign" onclick="uploadImg.del_share_img('+num+')"></i></li>';
        var li_length = parseInt($('.share-img-box li').length);
        if(li_length == 6) {       //显示上传图片的按钮
            $('li.add').hide();
        }
        $('.share-img-box li.add').before(item);
        $('.img-'+num).find('label').addClass('load');


    }
    if(status == 'insert') {
         var num = $('#upload_num').val();
        $('.img-'+num).find('label').addClass('load');
    }
}
/*by feng in 20151124 total*11*/
uploadImg.del_share_img = function(num){    //删除图片
    if(uploadImg.upComplete == 0) {
        alertBox('.alert-box','图片正在上传中...');
        return false;
    }
    $('.img-'+num).remove();    //移除该图片
    var li_length = parseInt($('.share-img-box li').length - 1);
    if(li_length == 5) {       //显示上传图片的按钮
        $('li.add').show();
    }
    $('#file-input').val('');
}

uploadImg._create = function (blob,dom_name,width,quality) {
    var img = new Image();
    img.src = blob;
    
    img.onload = function () {
        var that = this;

        //生成比例
        var w = that.width,
                h = that.height,
                scale = w / h;
        //w = obj.width || w;
        w = width;
        h = w / scale;

        //生成canvas
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        //$(canvas).attr({width : w, height : h});
        canvas.width=w;
        canvas.height=h;
        ctx.drawImage(that, 0, 0, w, h);

        /**
         * 生成base64
         * 兼容修复移动设备需要引入mobileBUGFix.js
         */
        var base64 = canvas.toDataURL('image/jpeg', quality || 0.8 );
        /*
         // 修复IOS
         if( navigator.userAgent.match(/iphone/i) ) {
         var mpImg = new MegaPixImage(img);
         mpImg.render(canvas, { maxWidth: w, maxHeight: h, quality: quality || 0.8});
         base64 = canvas.toDataURL('image/jpeg', quality || 0.8 );
         }
         */

        // 修复android
        if( navigator.userAgent.match(/Android/i) ) {
            var encoder = new JPEGEncoder();
            base64 = encoder.encode(ctx.getImageData(0,0,w,h), quality * 100 || 80 );
        }

    // 生成结果
    /*
     var result = {
     base64 : base64,
     clearBase64: base64.substr( base64.indexOf(',') + 1 )
     };
     */
    uploadImg.base64_img = base64;
    /*
     var img = new Image();
     img.src = base64_img;
     img.width=100;
     img.height=100;
     img.setAttribute("class","my_img");
     img.class='my_img';
     document.getElementById(dom_name).innerHTML="";
     document.getElementById(dom_name).appendChild(img);
     */
    uploadImg.uploadFile();
    };
}
    
uploadImg.uploadFile = function() {
    var fd = new FormData();
    fd.append("formFile",uploadImg.base64_img.substr(22));
    var xhr = new XMLHttpRequest();
    xhr.upload.addEventListener("progress", uploadImg.uploadProgress, false);
    xhr.addEventListener("load", uploadImg.uploadComplete, false);
    xhr.addEventListener("error", uploadImg.uploadFailed, false);
    xhr.addEventListener("abort", uploadImg.uploadCanceled, false);
    xhr.open("POST", uploadImg.uploadPath);
    xhr.send(fd);
}

uploadImg.uploadProgress = function(evt) {
    if (evt.lengthComputable) {
        var percentComplete = Math.round(evt.loaded * 100 / evt.total);
        document.getElementById(uploadImg.progressName).innerHTML = percentComplete.toString() + '%';
    }
    else {
        document.getElementById(uploadImg.progressName).innerHTML = 'unable to compute';
    }
}

uploadImg.uploadComplete = function(evt) {
    if (evt.target.responseText!=undefined && evt.target.responseText!=""){
        var dom2=document.getElementById("text_area");
        dom2.innerHTML=evt.target.responseText;
        var ret=JSON.parse(evt.target.responseText);
        var dom=document.getElementById("img_area");

        if (evt.target.responseText==-1){
            tipsBox.createAlertBox("表调戏宾哥，说好的带人脸图呢。。据说颜值越高摇中代金券价值越高哦");
        }else{
            dom2.innerHTML=ret["ret"];
            dom.innerHTML='<img src="'+ret["img"]+'"  class="my_img" />';
            var status = $('#upload_status').val();
            var orientation = $('#img_orientation').val();
            var host = 'http://'+window.location.host+'/';

            ret["img"] = ret["img"].replace('../',host);
            if(ret["img"].indexOf('http://') == -1) {
                ret["img"] = host + ret["img"];
            }

            if(status == 'add') {
                var num = parseInt($('#upload_total').val()) + 1;
                if(orientation != 6) {
                    $('.img-' + num).find('img').attr('src', ret["img"]);
                }
                $('#upload_total').val(num);
                var li_length = parseInt($('.share-img-box li').length - 1);
                if(li_length >= 6) {       //超过6张图片隐藏上传按钮
                    $('li.add').hide();
                }
            }
            
            if(status == 'insert') { 
                var num = $('#upload_num').val();
                if(orientation != 6) {
                    $('.img-' + num).find('img').attr('src', ret["img"]);
                }
            }

            if(orientation == 6) {
                setTimeout("uploadImg.trunImg('"+num+"')",3000);
            } else {
                uploadImg.uploadSuccess(num);
            }
        }
    }
}

uploadImg.uploadSuccess = function(num) {
    $('.img-'+num).find('img').load(function(){
        $('#file-input').val('');
        uploadImg.upComplete = 1;
        $('.share-img-box').find('label').removeClass('load');
        $('.share-img-box').find('label').attr('for','file-input');
        $('.img-'+num).find('i').show();    //图片加载完成才显示删除按钮
    });
}

uploadImg.trunImg = function(num) {
    var orderno = $('#upload_orderno').val();
    var url = 'upload.php?act=turn_img&folder='+uploadImg.folder+'&orderno='+orderno+'&num='+num;
    $.ajax({type:'get', url: url, data:{}, dataType: 'json',success:function(result){
        var img = result.data;
        var host = 'http://'+window.location.host+'/';
        img = img.replace('../',host);
        if(img.indexOf('http://') == -1) {
            img = host + img;
        }

        $('.img-'+num).find('img').attr('src',img);
        uploadImg.uploadSuccess(num);
    }});
}

uploadImg.uploadFailed = function(evt) {
    uploadImg.uploadFailedOpera('上传失败');
}

uploadImg.uploadCanceled = function(evt) {
    uploadImg.uploadFailedOpera('上传被取消');
}

uploadImg.uploadFailedOpera = function(tips) {
    $('.share-img-box').find('label').removeClass('load');
     var status = $('#upload_status').val();
     if(status == 'add') { 
         var num = parseInt($('#upload_total').val()) + 1;
         $('.share-img-box').find('li.img-'+num).remove();
    }

    $('#file-input').val('');
    uploadImg.upComplete = 1;
    $('.share-img-box').find('label').attr('for','file-input');
    alertBox('.alert-box',tips);
}

document.getElementById("file-input").onchange = function(e) {
    EXIF.getData(e.target.files[0], function() {
        $('#img_orientation').val(EXIF.getTag(this, 'Orientation'));
        uploadImg.fileSelected();
    });
}
var nodejs = {};

var special_queue = io.connect(_node_host2);
special_queue.eightTips = 0;
special_queue.on('connect', function () {});

special_queue.on('new kucun', function (data) { //修改特价水果库存量
    //var product = product_special_list[data.pid];
    //var id = product['id'];
    var kucan = data.num;
    //product_special_list[data.pid].kucun = kucan;
    $('.special_fruit_kucun_'+data.pid).html(kucan);
});

special_queue.on('timeout message', function (data) { //倒计时提醒
    var special_car = getCookie('special_car');
    if(special_car == null) {
        return false;
    }
    if(data == 2) {
        if(special_queue.eightTips == 0) {
            tipsBox.createAlertBox('闪购商品要在10分钟完成结算哦，你还有2分钟时间，超过时间，你的闪购会被别人抢走哦～');
            special_queue.eightTips = 1;
        }
    }
    if(data == 1) {
        var special_page = $('#special_page').val();
        if(special_page == 1) {
            for (var k in product_special_list){
                    var product = product_special_list[k];
                    var id = product['id'];
                    var title = product['title'];
                    var price = product['price'];
                    var kucan = $('.special_fruit_kucun_'+id).html();

                    delete product_special.join_special_car[id];
                    product_special.special_car(id,title,0,price);
                    product_special.recover_special_btn(id,title,price,kucan);
            }
        }

        product_special.headOffice = 0;
        setCookie('special_car', null, true);
        delCookie('special_car'); //删除特价水果cookie值
        product_special.join_special_car = {}; //清除已选上的特价水果
        var cart_page = $('#cart_page').val();
        if(cart_page != 1){ //重新计算价格
            common.tongji()
        } else {
            cart.count_show(0,0,"");
        }
        special_queue.eightTips = 0;
        product_special.createConfirmBox();
    }
 });

special_queue.on('total users', function(data){ //统计在线人数
    product_special.online_num = data;
    $('#online_num').html(data);
    $('.online_num').html(data);
    $('.over_time_num_people').html(data);
    $('#online_people_num').val(data);
});


/**
 * 街
 * 制作专题的商品
 */
var street = {};
street.menu = {};
street.product_list = {}; //商品列表
street.selected_product = {}; //选中的商品
street.class = { first_class: '', current_class: '', status: 0 };

/**
 * 街初始化
 * @method street.init
 */
street.init = function() {
    common.loading();
    //config.cart_init();
    common.user_login(street.readyProduct);
}

/**
 * 准备产品
 * @method street.readyProduct
 */
street.readyProduct = function() {
    var openid = user.userBase.bingo_openid;
    var url = api_host + "/Api/Product/product_spring";
    var data = { bingo_access_token: openid,bingo_openid: openid };
    $.ajax({type:'post', url: url, data: data, dataType: 'json', success: function(result){
        common.renderTpl("#app_content",'street/street_list',street.resetData(result.data));
        street.setCoverSize();     //设置年货街产品封面图片高度
        if(result.data == '') {
            common.noFoundResult('没有商品哦～');
        }
        common.loaded(2);
        $('#view_page').css('min-height',config.height);
    }});
}


/**
 * 获得当前类的产品
 * @method home.getCurrentClassProduct
 * @param {Object} Data
 * @return {Object}
 */
street.resetData = function(data) {
    var list = new Array();
    if(data != '') {
        for (var i in data) {
            var k = 0;
            var title = '';
            var items = new Array();
            for(var j in data[i]) {
                if(k == 0) {
                    title = data[i][j].class_mark2;
                }
                data[i][j].class_mark = '';
                data[i][j].for_new_user = 0;
                data[i][j].is_allow_buy = 1;
                data[i][j].allow_voucher = 1;
                data[i][j].danwei_intro = data[i][j].danwei;

                product_list[data[i][j].id] = data[i][j];

                items.push(data[i][j]);
                k++;
            }

            if(data[i] != '' ) {
                var param = {title: title, data: items};
                list.push(param);
            }
        }
    }
    var url = 'http://active.bingofresh.com/NewYearVoucher?openid='+user.userBase.bingo_openid+'&type=1';
    return { 'data': list,'url': url };
}


/**
 * 获得产品分类
 * @method home.getFirstClass
 */
street.getFirstClass = function() {
    var url = api_host + "/Api/Product/spring_nav";
    var openid = user.userBase.bingo_openid;
    var data = { bingo_access_token: openid, bingo_openid: openid};
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result) {
        if(result.status == 1) {
            street.menu = result.data.nav;
            if(result.data.nav != '') {
                for(var i in result.data.nav) {
                    street.class.current_class = result.data.nav[i].class_mark;
                    street.class.first_class = street.class.current_class;
                    break;
                }
            }
        }
        street.class.status = 1;
        street.readyProduct();
    }});
}

/**
 * 显示街坊的商品
 * @method street.showProduct
 */
street.showProductView = function(id) {
    if(id == 0) {
        $('#street-view').html('');
        return;
    }
    var data = product_list[id];
    if(data == undefined) {
        return false;
    }
    common.renderTpl("#street-view",'street/street_view', { data : data });
    $('#street-info-content').html(data.txt_content);
    tipsBox.tipsBoxCenter(".street-view-inner");
}

/**
 * 显示领取优惠券按钮
 */
street.showGetVoucherBtn = function() {
    var page = $('#page-mark').val();
    if(page != 'street') {
       return false;
    }
    var height = $('.street-voucher').height() + 30;
    if(config.scrollTop > height) {
        $('#street-voucher-btn').show();
    } else {
        $('#street-voucher-btn').hide();
    }
}

/**
 * 街头部菜单导航
 * @method street.menu
 */
street.header = function() {
    common.renderTpl('#app-header-main','street/street_header', { nav: street.menu });

    var partWidth = $('#current-part dl').width() + 20;
    var children =  $('#street-menue-ui').children().length;
    $('#current-part').css('width', partWidth + 'px');
    if(children >= 2) {
        var width = $('#street-menue-ui').width();
        $('#header-menue-ui li').css('width', parseInt(width / children) + 'px');
        if(home.cur_product_class == '') {
            home.cur_product_class = $('#street-menue-ui li').data('class');
        }
        if($('#page-mark').val() == 'home') {
            $('#menu-'+home.cur_product_class).addClass('current');
        }
        if($('#page-mark').val() == 'special') {
            $('#menu-special').addClass('current');
        }
    }
    navigation.setHeaderHeight();
}

/**
 * 街尾部菜单导航
 * @method street.footer
 */
street.footer = function() {
    $('#shopping-cart-box').addClass('street-cart-bg');
    $('#cart_num').addClass('street-cart-ft');
    //common.renderTpl('#app-footer-main','street/street_footer', {});
    //street.setShoppingCartSize();
}

/**
 * 设置购物车按钮颜色
 * @method street.setCartBtnColor
 */
street.setCartBtnColor = function() {
    var page = $('#page-mark').val();
    if(page == 'street') {
        $('.edit-product a').addClass('street-style');
        $('.shop-cart-top-tips').addClass('street-cart-ft');
        $('.item-num').addClass('street-cart-ft');
    }
}


/**
 * 设置购物车大小
 * @method street.setShoppingCartSize
 */
/*
street.setShoppingCartSize = function() {
    if(config.elementIsExist('street-cart-box')) {
        $('#street-cart-box').attr('style','');
        var width = $('#street-cart-box').width();
        $('#street-cart-box').css('width',width +'px');
        $('#street-cart-box').css('display','block');
    }

    if(config.elementIsExist('footer-product-btn')) {
        if($('#product-type').val() == 'normal') {
            return false;
        }
        navigation.setProductInfoBtn('footer-product-btn');
    }
    if(config.elementIsExist('footer-group-btn')) {
        if($('#product-type').val() == 'normal') {
            return false;
        }
        navigation.setProductInfoBtn('footer-group-btn');
    }
}*/

/**
 * 设置年货街产品封面图片高度    by feng
 * @method street.setCoverSize
 */
street.setCoverSize = function(){
    var width = $(window).width() - 16;
    var height = parseInt(parseFloat(width) * 0.453) + 'px';
    $('.street-box li').each(function(){
        $('.street-item-header a').css('height',height);
    });
}
/**
 * 街的购物车
 * 街的购物车操作
 */
var street_cart = {};
street_cart.num = 0;
street_cart.total = 0;

/**
 * 商品加按钮事件
 * @method street_cart.plusBtn
 * @param {Number} id 商品id
 * @param {Object} event 事件
 */
street_cart.plusBtn = function(id, event) {
    var p = product_list[id];
    var ret = street_cart.plusOpera(p);
    if (ret == false){
        return false;
    }

    tongji();
    show_user_buy(p,event);

    if(event == "cartinfo"){     //用户购物车指定产品加1 +1c处理
        var item_price = $("#item-price-"+p.id).text();
        var item_num =  Number($("#item-num-"+p.id).text()) + 1;
        var item_total_price = parseFloat(item_price) + parseFloat(p.price);
        if(item_total_price > parseInt(item_total_price)){
            item_total_price = item_total_price.toFixed(2);
        }
        $("#item-price-"+p.id).text(item_total_price);
        $("#item-num-"+p.id).text(item_num);
    }

}

/**
 * 商品数量加一
 * @param {Object} p
 * @returns {boolean}
 */
street_cart.plusOpera = function(p) {
    if (p == undefined){
        return false;
    }

    if (p.kucun < 1) {
        return false;
    }

    if (p.kucun - p.num <= 0){
        alertBox('.alert-box',p.title+'库存不足,您可以选购别的商品哦');
        return false;
    }

    if (p.num == undefined || p.num == 0){
        p.num = 1;
    } else {
        p.num++;
    }

    operateCart(p);
    //street_cart.AddCart(p.id,p.title,p.num,p.price);
    return true;
}

/**
 * 商品的数量减一
 * @method street_cart.subtractBtn
 * @param {Number} id 商品id
 * @param {Object} event 事件
 */
street_cart.subtractBtn = function(id, event){
    var p=product_list[id];
    do_subtract(p);
    tongji();
    show_user_buy(p);
    if(event == "cartinfo"){     //用户购物车指定产品减1 -1处理
        var item_price = $("#item-price-"+p.id).text();
        var item_num =  Number($("#item-num-"+p.id).text()) - 1;
        var item_total_price = parseFloat(item_price) - parseFloat(p.price);
        if(item_num == 0){
            $("#iteminfo-"+p.id).remove();       //移除该商品
            if($("#cart_num").html() == 0){     //当没有产品时关闭清空用户购物车
                home.my_cart_hide();
            }
            var windowHeight = $(window).height() - 100;
            var height = $('.shop-cart-box').height();
            //不需要滚动时隐藏到底提示
            if(height < parseInt(windowHeight) && $('.shop-cart-bottom-tips').css('display') == 'block') {
                $('.shop-cart-bottom-tips').hide();
            }
        }else{
            if(item_total_price > parseInt(item_total_price)){
                item_total_price = item_total_price.toFixed(2);
            }
            $("#item-price-"+p.id).text(item_total_price);
            $("#item-num-"+p.id).text(item_num);
        }
    }
}


/*
function do_plus(p){

    var checkNum = p.restriction!=undefined?p.restriction:0;

    if (p==undefined){
        return false;
    }
    if (p.kucun < 1) {
        return false;
    }
    if (p.kucun-p.num <= 0){
        alertBox('.alert-box',p.title+'库存不足,您可以选购别的商品哦');
        return false;
    }
    if(checkNum>0 && p.num>=checkNum) {
        alertBox('.alert-box',p.title+'商品限量购买，不能再多了');

        return false;
    }
    if (p.num==undefined || p.num==0){
        p.num=1;
    }else{
        p.num++;
    }

    street_cart.AddCart(p.id,p.title,p.num,p.price);
    return true;
}

function do_subtract(p){
    if( p== undefined ){
        return false;
    }
    if (p.num == undefined || p.num <= 0 ){
        return false;
    } else {
        p.num--;
    }
    street_cart.AddCart(p.id,p.title,p.num,p.price);
    return true;
}

 */

/*

config.AddCart('street_cart',1,'test',1,10);
config.AddCart('street_cart',2,'keepsilent',1,21);
config.AddCart('street_cart',1,'test',23,10);
config.AddCart('street_cart',3,'test',3,11);
config.AddCart('street_cart',3,'test',4,11);
console.log(common.getCookie('street_cart'));

console.log(common.subtotal_car('street_cart'));

in_buy_car(1,'test',1,10);
in_buy_car(2,'keepsilent',1,21);
in_buy_car(1,'test',23,10);
in_buy_car(3,'test',3,11);
in_buy_car(3,'test',4,11);
console.log(getCookie('buycar'));*/
/**
 * 模版 template 使用函数
 */

template.helper('numFormat', function (nStr) { //数字格式化
    return common.numFormat(nStr);
});

template.helper('numFormat_score', function (nStr,number) { //数字格式化
	nStr = nStr * number;
    return common.numFormat(nStr);
});

template.helper('dateFormat', function (date, format) { //日期格式化
    return common.dateFormat(date, format);
});

template.helper('deal_with_status', function (status) {
    return recharge.deal_with_status(status);
});

template.helper('count_down', function (id, next_time, serverTime) {
    return common.count_down(id, next_time, serverTime);
});

template.helper('sendTimeFormat', function (data, type) { //送货日期格试化
    return common.sendTimeFormat(data, type);
});

/**
 * 数字如果是正数,格式化成正数,不是正数，保留数字
 * @param {Number} number 数字
 * @param {Number} decimal 保留小数点,默认是2位小数
 * @return {Number}
 */
template.helper('setNumberIntegral', function (number, decimal) {
    return base.setNumberIntegral(number,decimal);
});

/**
 * 数字如果是正数,格式化成正数,不是正数，保留数字
 * @param {Number} number 数字
 * @param {Number} decimal 保留小数点,默认是2位小数
 * @return {Number}
 */
template.helper('setNumberDecimals', function (number, decimal) {
    return base.setNumberDecimals(number,decimal);
});

/**
 * 传入数字返回星期名称，1代表星期一/周一，7代表星期天/周日、
 * @param {Number} number 代表星期的数字
 * @param {String} type 类型，0是周一，1是星期一
 * @return {String}
 */
template.helper('numberWeek', function(number,type){
	return base.numberWeek(number,type);
});

/**
 * 获取下周某星期的日期
 * @param {Number} weeknumber 星期几，1代表星期一，7代表星期日
 * @return {string}
 */
template.helper('nextWeekDate', function(weeknumber){
    return base.nextWeekDate(weeknumber);
});
/**
 * 省钱快报
 */
 var thrifty = {};
thrifty.alldata = {};       //所有数据
thrifty.alldata.tejia = {}      //特价数据
thrifty.alldata.special_list = {}       //抢购数据
thrifty.alldata.qiangname = "";    //每日抢购名称
thrifty.daojishi_over_status = 1;     //抢购倒计时
thrifty.online_num = 0;
thrifty.join_special_car = {};
/*
 *数据模板配置
*/
 thrifty.show = function(){

    thrifty.daojishi_over_status = 1
    //获取当前日期并格式化
    var myDate = new Date();
    myDate.toLocaleDateString();
    var time = common.dateFormat(myDate,'yyyy-MM-dd');
    thrifty.alldata.datetime = time;
    //获取当前分店
    var city = select_area.city_list[user.userBase.city_code];
    thrifty.alldata.short_name = city.replace("市", "") + user.userBase.short_name;
    //获取用户头像
    thrifty.alldata.user_img = user.userBase.avatar;
    thrifty.alldata.vip_code = user.userBase.vip_code;
    // console.log(thrifty.alldata.vip_code);

    var open = user.userBase.bingo_openid;
    var url = api_host + "/Api/TempActivity/get_save_money_info";
    var data = { bingo_access_token: open, bingo_openid: open };
    $.ajax({type:'post',url:url,data:data,dataType:'json',success:function(result){
        // console.log(result);

        result.data.tejia_data.save = 0;
        if(result.data.tejia_data != ""){
            if(parseInt(result.data.tejia_data[0].shichangjia) > 0) {
                result.data.tejia_data.save = result.data.tejia_data[0].shichangjia - result.data.tejia_data[0].price;
            } else if(result.data.tejia_data.save <= 0 &&  parseInt(result.data.tejia_data[0].original_price) > 0) {
                result.data.tejia_data.save = result.data.tejia_data[0].original_price - result.data.tejia_data[0].price;
            }
            if(result.data.tejia_data.save > parseInt(result.data.tejia_data.save)) {
                result.data.tejia_data.save = result.data.tejia_data.save.toFixed(1);
            }
        }

        thrifty.alldata.rest = result.data;

        var html = template('thrifty', thrifty.alldata);
        $("#app_content").html(html);
        $("#app_content").css("padding-bottom","0px;");

        var data_number = [];
        var data_type = [];
        $.each(result.data.save_money_data, function(i){
            data_number.push(i);
            data_type.push(result.data.save_money_data[i].type_save);
        });
        if($.inArray("qianggou", data_type) >= 0){
            var arr_num = $.inArray("qianggou", data_type);
            var data_type_arrnum = data_number[arr_num];
            thrifty.alldata.qiangname = result.data.save_money_data[data_type_arrnum].title;
        }
        thrifty.item_snapup();

    }});

    common.loaded(1);
 }
/*
 *每日抢购
*/
thrifty.item_snapup = function(){
    if($('#thrifty_qiang').length <= 0){
        return false;
    }
    var url= api_host + "/Api/Product/special_list2";
    var openid=user.userBase.bingo_openid;
    thrifty.daojishi_over_status = 1;
    if (openid==undefined || openid==null || openid.length==0){
        return false;
    }
    var data={
        bingo_access_token:openid
        ,bingo_openid:openid
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result){
        var active_id = 0;
        var next_active_current = 0;

        result.data.now_active_status = 0;
        result.data.next_active_status = 0;
        result.data.active_is_ready = 0;
        result.data.now_active_info = '';
        result.data.next_active_info = '';
        result.data.special_list = '';
        result.data.online_num = thrifty.online_num;
        result.data.join_special_car = thrifty.join_special_car;

        for (var k in result.data.hd_list) {
            result.data.hd_list[k].index = k;
            result.data.hd_list[k].next_active_current = 0;
            if((result.data.hd_list[k].is_cur == 1 || result.data.hd_list[k].is_cur == -1) && result.data.special_list == '') {
                active_id = result.data.hd_list[k].id;
                result.data.special_list = result.data.hd_list[k].special_list;
                if(result.data.active_not_over == 0 && result.data.hd_list[k].is_cur == -1 ) {
                    result.data.active_not_over = 1;
                }
                if(result.data.hd_list[k].is_cur != 1) {
                    thrifty.daojishi_over_status = 0;
                }
            }
            if(result.data.hd_list[k].is_cur == 1) {
                result.data.now_active_status = 1;
                if(result.data.now_active_info == '') {
                    result.data.now_active_info = {active_id:result.data.hd_list[k].id, active_name:result.data.hd_list[k].title,start_time:result.data.hd_list[k].st};
                }
            }
            if(result.data.hd_list[k].is_cur == -1) {
                result.data.next_active_status = 1;
                if(result.data.next_active_info == '') {
                    result.data.next_active_info = {id:k,active_id:result.data.hd_list[k].id,active_name:result.data.hd_list[k].title,start_time:result.data.hd_list[k].st};
                }
                if(next_active_current == 0 && result.data.now_active_status == 0) {
                    next_active_current = 1;
                    result.data.hd_list[k].next_active_current = 1;
                }
            }
        }
        result.data.img_v = _img_v;
        result.data.next_active_status = (result.data.now_active_status == 1) ? 0 : result.data.next_active_status; //特价是否有下一场
        result.data.special_status = (result.data.now_active_status || result.data.next_active_status )  ? 1 : 0; //特价水果是否结束了
        result.data.active_is_ready = (result.data.special_list != '')  ? 1 : 0; //特价水果是否准备好水果
        result.data.qiangname = thrifty.alldata.qiangname;
        // console.log(thrifty.alldata.qiangname);

        var html = template("thrifty_qiang", result.data);
        $("#thrifty_qiang").html(html);

        if(result.data.next_active_status == 1) { //显示预购倒计时
            thrifty.daojishi(result.data.next_active_info.start_time,result.data.time);
        }

        if(result.data.special_list != '') { //特价水果列表
            for (var k in result.data.special_list){
                result.data.special_list[k]['num'] = 1;
                product_special_list[result.data.special_list[k]["id"]] = result.data.special_list[k];
                product_special_list[result.data.special_list[k]["id"]]['active_id'] = active_id;
            }
        }

        thrifty.getNewKucun();     //获取当前库存
    }});
}

thrifty.getNewKucun = function() {
    var products=[];
    var timestamp = Date.parse(new Date());
    for ( var k in product_special_list) {
        products.push(product_special_list[k]['id']);
    }
    var pids = products.join(",");
    var aid = $('#thriftyactive_id').val();
    var data={lid:user.userBase.league_id,aid: aid,uid:user.userBase.id,pids:pids,timestamp:timestamp};
    $.ajax({type:'get', url:_node_host3+"/getNewKucun", data:data, dataType:'json', success:function(result){
        if(result.status > 0 ) {
            if(result.data[0]['id'] != undefined) {
                var kucan = result.data[0]['num'];
                if(kucan <= 0 && result.data[0]['is'] == 0  && thrifty.daojishi_over_status == 1 ) {      //库存已经没了
                    $("#special_num").html("抢光了");
                }
            }
        } else {
            tipsBox.createAlertBox(result.data);
        }
    }});
}

thrifty.daojishi = function(next_time,serverTime){      //倒计时计时
    var myDate = new Date();
    var next_str=myDate.getFullYear()+"/"+(myDate.getMonth()+1)+"/"+myDate.getDate()+" "+next_time+":00";
    var t=(new Date(next_str)).getTime()/1000;
    var now = serverTime;
    if (isNaN(t) || isNaN(now)){
        alert("时间出错了");
        return false;
    }
    if(t < now){
        t += 86400;
    }
    if(daojstt){
        clearTimeout(daojstt);
        daojstt=null;
        delete daojstt;
        $("#next_special_time").html('');
    } else {
        setTimeout(jsq,1000);
    }

    var Times = t - now;
    var online_show = 0;
    function jsq(){
        if (Times >= 0){       //还没开启
            var D = parseInt(Times / 86400);
            var H = parseInt((Times - D * 86400)/3600);
            var i = parseInt((Times -D * 86400 - H * 3600) / 60);
            var s = Times - H * 3600-i * 60-D * 86400;
            var html = '';
            if(Times < 600 && online_show == 0) {
                online_show = 1;
                // $('#ten_minute_online').show();
            }
            if (D != 0) {
                html = "<span>" + D + "</span>天<span>" + H + "</span>小时<span>" + i + "</span>分<span>" + s + "</span>秒";
            } else {
                if(H != 0){
                    html = "<span>" + H + "</span>小时<span>" + i + "</span>分<span>" + s + "</span>秒";
                } else {
                    if(i != 0){
                        html = "<span>" + i + "</span>分<span>" + s + "</span>秒";
                    } else {
                        html = "<span>" + s + "</span>秒";
                    }
                }
            }
            $("#next_special_time").html(html);
            Times--;
            clearTimeout(daojstt);
            daojstt = setTimeout(jsq,1000);
        } else {     //已经开启
            // console.log("开始抢购");

            clearTimeout(daojstt);
            var name = $('#thriftnext_active_name').val();
            var html = '<h3><span>' + name + '</span>已开始</h3><p>数量有限，先到先得</p>'
            $('#thriftnow_active').html(html);

            thrifty.daojishi_over_status = 1;
        }
    }
    jsq();
};
var tracking = {}
tracking.getNormalModel = function(orderno) { //正常模式的订单跟踪
    var url = api_host+"/Api/Deliveryman/deliveryman_gps";
    var openid = user.userBase.bingo_openid;
    if (openid == undefined || openid == null || openid.length == 0){
        return false;
    }
    var data={
        bingo_access_token:openid
        ,bingo_openid:openid
        ,orderno:orderno
    };
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result) {
        var j = 0;
        var op_time = new Array();
       
        for (var i = result.data.op_time.length - 1; i >=0 ;i--) {
            op_time[j] = result.data.op_time[i];
            j++;
        }
        result.data.op_time = op_time;
        var trackingStatus = result.data.op_time[0]['opstatus'];
        var html = template('tracking_noram_model', result.data);
        $("#app_content").html(html);
      
       switch(parseInt(trackingStatus)) {
            case 0:
            case 3:
            case 11:
            case 13:   
                $('.tracking-tips').show();
                $('.tracking-tips').html('等待送货员取件');
                break;
            case 1:
                var start = parseInt(new Date().getTime() / 1000);
                var remainTime = common.remainTime(start,result.data.forwardTime);
                $('.scheduled-time').show();
                $('.scheduled-time span').html('预计'+ remainTime+'后送达');
                $('.order-remain').show();
                $('.order-remain').html('您之前还有'+result.data.orders+'份订单');
                $('.tracking-status-info').css('marginBottom','5%');
                break;
            case 2:
                var remainTime = common.remainTime(result.data.op_time[1].create_time,result.data.op_time[0].create_time);
                $('.scheduled-time').show();
                $('.scheduled-time span').html('总共花费'+ remainTime);
                $('.order-remain').show();
                $('.order-remain').html(common.dateFormat(result.data.op_time[0].create_time * 1000,'d日h:m分') + '收到货');
                $('.tracking-status-info').css('marginBottom','5%');
                $('.finsh').show();
                $('.tracking-main table tr td span.send-time').css('background','#9a9a9a');
                break;
        }
        common.loaded(0);
        //设置顶部
        navigation.simpleStyle("订单跟踪");
        $("#header-common-main span").css("font-size","1.2em");
        //设置底部
        navigation.commonFooterTpl("查看地图模式", "#/tracking/" + result.data.orderno + "/map");
    }});
}

tracking.getMapModel = function(orderno) { //地图模式的订单跟踪
    var url = api_host+"/Api/Deliveryman/deliveryman_gps";
    var openid = user.userBase.bingo_openid;
    if (openid == undefined || openid == null || openid.length == 0){
        return false;
    }
    var data={
        bingo_access_token:openid
        ,bingo_openid:openid
        ,orderno:orderno
    };
   
    $.ajax({type:'post',url:url,data:data,dataType: 'json',success:function(result) {
        var j = 0;
        var op_time = new Array();
        var regular = new RegExp('E');
        if(regular.test(result.data.lat) || regular.test(result.data.lng) ) {
            result.data.lng = '';
            result.data.lat = '';
        }
       
        if(result.data.op_time != '') {
            for (var i = result.data.op_time.length - 1; i >=0 ;i--) {
                op_time[j] = result.data.op_time[i];
                j++;
            }
        }
       
        var trackingStatus = result.data.opstatus;
        result.data.op_time = op_time;
        result.data.city = select_area.city_list[result.data.city_code];
        result.data.trackingStatus = trackingStatus;
        result.data.api_host = api_host;
        result.data.openid = openid;
        result.data.orderno = orderno;
        var html = template('tracking_map_model', result.data);
        $("#app_content").html(html);
        $('#mapBox').css('height',parseInt($(window).height() * 0.72) +'px');
       
        switch(parseInt(trackingStatus)) {
            case 0:
            case 3:
                /*
                var time = common.dateFormat(result.data.op_time[0].create_time * 1000,'yyyy.MM.dd日 : h:m');
                var title = '店长收到你的订单，已帮你挑选最好的水果，等待派送';
                $('.cover').attr('src','./ui/images/tracking/map_order_01.png');
                $('.address').html(result.data.addr1+result.data.addr2+result.data.addr3);
                $('.info').html(title);
                $('.date').html(time);
                $('.order-send-info dl dt').html(title);
                $('.order-send-info dl dd').html(time);
                break; */
            case 11:
            case 13:
                var time = common.dateFormat(result.data.op_time[0].create_time * 1000,'yyyy年MM月dd日 h:m');
                $('.cover').attr('src','./ui/images/tracking/map_order_02.png');
                $('.address').html(result.data.addr1+result.data.addr2+result.data.addr3);
                $('.info').html('店长收到你的订单，已帮你挑选最好的产品，等待派送');
                $('.date').html(time);
                $('.order-send-info dl dt').html('店长收到你的订单，已帮你挑选最好的产品，等待派送');
                $('.order-send-info dl dd').html(time);
                break;
           case 1:
                var start = parseInt(new Date().getTime() / 1000);
                var remainTime = common.remainTime(start,result.data.forwardTime);
                $('.map-header-inner dl dt').html('预计'+ remainTime+'后送达');
                $('.map-header-inner dl dt strong').css('fontWeight', 'normal');
                $('.map-header-inner dl dd').html('您之前还有'+result.data.orders+'份订单派送');

                var time = common.dateFormat(result.data.op_time[0].create_time * 1000,'yyyy年MM月dd日 h:m');
                $('.cover').attr('src','./ui/images/tracking/map_order_03.png?v=2015052401');
                $('.address').html(result.data.addr1+result.data.addr2+result.data.addr3);
                $('.info').html(result.data.delivery_name+'已出发为你送货啦，你之前有'+result.data.orders+'份订单');
                $('.date').html(time);
                $('.order-send-info dl dt').html(result.data.delivery_name+'送货员已取货<span id="now_address"></span><span id="distance"></span>');
                $('.order-send-info dl dd').html(time);
                break;
          case 2:
                var remainTime = common.remainTime(result.data.op_time[1].create_time,result.data.op_time[0].create_time);
                var time = common.dateFormat(result.data.op_time[0].create_time * 1000,'yyyy年MM月dd日 h:m');
                var sendTime = common.dateFormat(result.data.op_time[0].create_time * 1000,'dd日h:m');
                $('.map-header-inner dl dt').html('订单已完成，总共花费'+remainTime+'送到您手中');
                $('.map-header-inner dl dt').css('textAlign', 'left');
                $('.map-header-inner dl dt strong').css('fontWeight', 'normal');
                $('.map-header-inner dl dt').css('marginLeft', '5%');
                $('.map-header-inner dl dt').css('marginRight', '5%');
                $('.map-header-inner dl dd').html('');
                $('.cover').attr('src','./ui/images/tracking/map_order_04.png');
                $('.info').html(result.data.delivery_name+'已经把产品送给您啦。您在'+result.data.addr1+result.data.addr2+result.data.addr3+'签收了来自缤果的产品！');
                $('.date').html(time);
                $('.order-send-info dl dt').html('你的订单已完成，'+sendTime+'在'+result.data.addr1+result.data.addr2+result.data.addr3+'成功收货');
                $('.order-send-info dl dd').html(time);
                break;
        }
        common.loaded(0);
        navigation.simpleStyle("地图模式");
        $("#header-common-main span").css("font-size","1.2em"); 
    }});
} 

tracking.showBuyFruit = function() {
    var status = $('#tracking-fruit-table').val();
    if(status == 1) {
        $('.tracking-fruit-inner h1 img').attr('src','./ui/images/tracking/tracking_fruit_top_btn.png');
        $('.tracking-fruit-table').hide();
        $('#tracking-fruit-table').val(0);
    } else {
        $('.tracking-fruit-inner h1 img').attr('src','./ui/images/tracking/tracking_fruit_down_btn.png');
        $('.tracking-fruit-table').show();
        $('#tracking-fruit-table').val(1);
    }
    
}

tracking.tipsBox = function(status) {
    if(status == 0) {
        $('.map-sinding-wrap').hide();
    } else {
        $('.map-sinding-wrap').show();
    }
}
tracking.getDistance = function(distance) {
    $('#distance').html(distance);
}
tracking.getNowAddress = function(address) {
    $('#now_address').html(address);
}

tracking.setSendAddress = function(status) {
    var trackingStatus = $('#trackingStatus').val();
    if(status == 1) {
        var bingo_position = ($('#bingo_position').val() != '') ? $('#bingo_position').val() : $('#lng_address').val();
        $('.address').html(bingo_position);
    } else {
        $('.address').html($('#bingo_send_address').val());
    }
}
tracking.setBingoPosition = function(address) {
    $('#bingo_position').val(address);
}
 
/**
 * 视频播放
 */
var video = {}

/**
 * 播放视频按钮
 * @method video.playVideoBnt
 * @param {String} src 视频数径
 * @param {String} open 按钮点击统计
 */
video.playVideoBnt = function(src,open) {

    if(webDevice.networkType != '' && webDevice.networkType != 'wifi') {
        if(!confirm('亲，您不是在wifi网络，是否继续播放')) {
            return false;
        }
    }

    var videoBox = '';
    videoBox = '<div id="video-mask" onclick="video.colseVideoBtn()"></div>';
    videoBox += '<div id="video-view-box"></div>';
    videoBox += '<div class="video-colsebtn"><a href="javascript:video.colseVideoBtn();">关闭视频</a></div>';
    $('#video-box').html(videoBox);
    $('#video-box').show();

    var videoMyselfBox = '';
    videoMyselfBox = '<param name="wmode" value="opaque"/>';
    videoMyselfBox = '<video id="video-myself-box"  style="display: none;" onclick="video.pausedVideoBtn()" src="" width="100%"  wmode="opaque" webkit-playsinline>'+videoMyselfBox+'</video>';
    $('#video-view-box').html(videoMyselfBox);
    $('#video-myself-box').attr('src',src);

    $('#video-view-box').css('height',config.width * 9 / 16);
    document.getElementById('video-myself-box').play();
    $('#video-myself-box').show();


    //按钮点击统计
    var page = $('#page-mark').val();
    if(page == "product-info" && open != "open"){
        common.buttonClikcStatistics("view","view_video","视频播放");
    }else if(page == "home"){
        common.buttonClikcStatistics("index","index_playVideo","视频播放");
    }
}

/**
 * 视频播放与暂停
 * @method video.pausedVideoBtn
 */
video.pausedVideoBtn = function() {
    var _thisVideo = document.getElementById('video-myself-box');
    if (_thisVideo.paused) {
        $('#video-myself-box').removeAttr('controls');
        _thisVideo.play();
    } else {
        _thisVideo.pause();
        $('#video-myself-box').attr('controls','controls');
    }
}

/**
 * 关闭视频
 * @method video.colseVideoBtn
 */
video.colseVideoBtn = function() {
    var _thisVideo = document.getElementById('video-myself-box');
    _thisVideo.pause();

    $('#video-view-box').html('');
    $('#video-box').hide();
}



video.playVideo = function(id, src) {
    if(webDevice.networkType != '' && webDevice.networkType != 'wifi') {
        if(!confirm('亲，您不是在wifi网络，是否继续播放')) {
            return false;
        }
    }

    $('div.video-wrap').removeClass('video-mBottom');
    $('div.product-title-header').removeClass('video-mTop');
    $('div.product-title-header').removeClass('video-pBottom');
    $('div.product-notice-inner').removeClass('video-top');
    $('div.product-shopping').removeClass('video-top');
    $('.video-fullSreen').hide();
    $('.video-close').hide();
    $('.video-pause').hide();
    $('.video-wrap').hide();
    $('div.video-loading').hide();
    $('.video-play').show();
    $('.product-cover').show();

    var _thisVideoSrc = '<video id="product-video-'+id+'"  onplaying="video.loading('+id+')" class="video-style" src=""  wmode="opaque"  webkit-playsinline> <param name="wmode" value="opaque" /></video>';
    var _cover = $('#product-item-'+id).find('a.product-cover');
    _cover.hide();
    $('#product-item-'+id).find('div.video-play').hide();
    $('#product-item-'+id).find('div.video-fullSreen').show();

    $('#product-item-'+id).find('div.video-wrap').html(_thisVideoSrc).show();
    $('#product-video-'+id).attr('src',src);
    $('#product-video-'+id).css('width',_cover.css('width'));
    $('#product-video-'+id).css('height',_cover.css('height'));
    $('#product-video-'+id).attr('width',_cover.width());
    $('#product-video-'+id).attr('height',parseInt(_cover.css('height').replace('px','')));
    video.scan_code_video(id,0);
    video.pausedLoading(id);
    var u = navigator.userAgent;
    if(u.indexOf('Android') > -1 || u.indexOf('Linux') > -1){
        $('#product-item-'+id).find('div.video-wrap').addClass('video-mBottom');
        $('#product-item-'+id).find('div.product-title-header').addClass('video-mTop');
        $('#product-item-'+id).find('div.product-title-header').addClass('video-pBottom');
        $('#product-item-'+id).find('div.product-notice-inner').addClass('video-top');
        $('#product-item-'+id).find('div.product-shopping').addClass('video-top');
        $('#video-close-'+id).show();
    }
    var _thisVideo = document.getElementById('product-video-'+id);
    _thisVideo.play();
}
video.loading = function(id) {
    $('#product-item-'+id).find('div.video-loading').hide();
}
video.pausedVideo = function(id) {
    var _thisVideo = document.getElementById('product-video-'+id);
    if(_thisVideo.paused) {
        _thisVideo.play();
        $('#product-item-'+id).find('div.video-pause').hide();
        $('#product-item-'+id).find('div.video-fullSreen').show();
        $('#product-item-'+id).find('div.video-loading').hide();

        $('#product-item-'+id).find('a.product-cover').hide();
        $('#product-item-'+id).find('div.video-wrap').show();
        $('#video-close'+id).show();
    } else {
        _thisVideo.pause();
        video.pausedHide(id);
        $('#product-item-'+id).find('div.video-fullSreen').hide();
        $('#product-item-'+id).find('div.video-loading').hide();

        $('#product-item-'+id).find('div.video-pause').hide();
        $('#product-item-'+id).find('a.product-cover').show();
        $('#product-item-'+id).find('div.video-wrap').hide();
        $('#product-item-'+id).find('div.video-play').show();

        var u = navigator.userAgent;
        if(u.indexOf('Android') > -1 || u.indexOf('Linux') > -1){
            $('div.video-wrap').removeClass('video-mBottom');
            $('div.product-title-header').removeClass('video-mTop');
            $('div.product-title-header').removeClass('video-pBottom');
            $('div.product-notice-inner').removeClass('video-top');
            $('div.product-shopping').removeClass('video-top');
            $('#video-close-'+id).hide();
        }
        video.scan_code_video(id,1);
    }
}

video.pausedHide = function(id) {
    $('#product-item-'+id).find('div.video-pause').show();
    var _thisPause = $('#product-item-'+id).find('div.video-pause-inner');
    var _height = _thisPause.height();
    var _cover =  $('#product-video-'+id).height();
    _thisPause.css('marginTop', ((_cover - _height ) / 2 )+'px');
}

video.pausedLoading = function(id) {
    $('#product-item-'+id).find('div.video-loading').show();
    var _thisPause = $('#product-item-'+id).find('div.video-loading-inner');
    var _height = _thisPause.height();
    var _cover =  $('#product-video-'+id).height();
    _thisPause.css('marginTop', ((_cover - _height ) / 2 )+'px');
}

video.fullScreen = function(id) {
    var _thisVideo = document.getElementById('product-video-'+id);
    _thisVideo.webkitEnterFullscreen();
}

/**
 * 扫码视频
 * @param {int} id 元素id
 * @return {void}
 */
video.scan_code_video = function(id,status) {
    if($('#scan-code-page').val() != 1) {
        return false;
    }
    if(status == 0) {
        var width = $(window).width();
        $('#product-video-' + id).css('width', width + 'px');
        $('#product-video-' + id).css('height', 'auto');
        $('.praise-btn').hide();
        $('.video-style').css('borderRadius',0);
    } else {
        $('.praise-btn').show();
    }
}
/**
 * 缤果会员
 */
var vip = {};
vip.balance = 0;     //余额
vip.getData = null;   //member_handle接口数据
vip.myScore = 0;    //我的积分
vip.useMyScore = 0;   //使用的积分
vip.payMoney = 0;    //微信支付的金额

/**
 * 缤果VIP入口
 * @method vip.entrance
 * @param {String} type 类型，0是正常进入，1是开通成功进入
 */
vip.entrance = function(type){
	// window.location.reload()
	var url = api_host + "/Api/Users/member_handle";
	var openid = user.userBase.bingo_openid;
	if (openid == undefined || openid == null || openid.length == 0){
	    return false;
	}
	var data = {
		bingo_access_token: openid
		,bingo_openid: openid
	};
	$.ajax({type: 'post', url: url, data: data, dataType: 'json', success: function (result) {
		vip.getData = result.data;
		var data = user.userBase;
		data.success = type;
		data.disableMemberTime = common.dateFormat(new Date(data.disable_member_time*1000),"yyyy-M-d");
		data.giftVipScore = result.data.gift_vip_score;
		data.giftVipTime = result.data.gift_vip_time;
		data.yifan = parseInt(result.data.yifan);
		data.shengyu = parseInt(result.data.shengyu);
		data.benci = base.setNumberDecimals(result.data.benci);
		data.bencishenyu = base.setNumberDecimals(100 - data.benci);
		if(data.shengyu == 0){
			data.benci = 100;
		}
		common.renderTpl("#app_content",'vip/vip',data);
		//设置导航样式
		navigation.commonStyle();
		common.loaded(0);
	}});
}

/**
 * 成为缤果VIP
 * @method vip.getVip
 */
vip.getVip = function(){
	if(vip.getData != null){
		vip.buyDataEditor(vip.getData);
		return false;
	}
	var url = api_host + "/Api/Users/member_handle";
	var openid = user.userBase.bingo_openid;
	if (openid == undefined || openid == null || openid.length == 0){
	    return false;
	}
	var data = {
		bingo_access_token: openid
		,bingo_openid: openid
	};
	$.ajax({type: 'post', url: url, data: data, dataType: 'json', success: function (result) {
		if(result.status != 1){
			tipsBox.createAlertBox(result.data);
			return false;
		}
		vip.buyDataEditor(result.data);
	}});
}

/**
 * 渲染缤果会员购买页面数据
 * @method vip.buyDataEditor
 * @param {Object} data 接口数据
 */
vip.buyDataEditor = function(data){
	vip.myScore = data.user_score_sum;
	vip.balance = base.setNumberDecimals(data.balance);
	data.userScoreSumso = parseInt(data.user_score_sum*100);
	common.renderTpl("#app_content",'vip/get_vip',data);
	//设置导航样式
	navigation.commonStyle();

	var moneyList = [];
	for(var i = 0, len = data.buy_time.length; i < len; i++){
		var money = base.setNumberDecimals(data.buy_time[0].money);
		moneyList.push(money);
	}
	var minValue = base.setNumberDecimals(Math.min.apply(null,moneyList));
	if(vip.balance > 0 && vip.balance >= minValue){
		$('#balancePay').show();
	}
	//计算可用积分
	vip.useScore();
	$('#vip-payType').show();   //显示微信支付
	//设置底部按钮
	var btnHtml = '确认支付&nbsp;&yen;&nbsp;' + data.buy_time[0].money;
	navigation.commonFooterTpl(btnHtml,'','vip.submitPay()');
	common.loaded(0);
}

/**
 * 选择开通时长
 * @method vip.selectItem
 * @param {Objct} _this dom对象
 */
vip.selectItem = function(_this){
	if(_this.hasClass('current')){
		return false;
	}

	$("#vipOpenTime a").each(function(){
		$(this).removeClass('current');
	});
	_this.addClass('current');

	vip.useScore();
}

/**
 * 计算积分抵扣金额
 * @method vip.useScore
 * @param {Number} type 2为选中积分
 */
vip.useScore = function(type){
	var price = 0;
	$("#vipOpenTime a").each(function(){
		if($(this).hasClass('current')){
			price = base.setNumberDecimals($(this).data('price'));
		}
	});
	var userScoreSum = 0;
	var footerHtml = '确认支付';
	var userScoreMoney = base.setNumberDecimals(parseInt(vip.myScore)/100);
	var gapPrice = (price*10 - userScoreMoney*10)/10;
	if(gapPrice < 0){
		//积分足够支付
		if($('#vip_score_sum').prev().hasClass('current')){
			//选中了积分支付
			$('#vip-payType').hide();
		}else{
			footerHtml += '&nbsp;&yen;&nbsp;' + price;
		}
		userScoreSum = price;
		if(type == 2){
			$('#vip-payType').hide();
		}
	}else{
		if($('#vip_score_sum').prev().hasClass('current')){
			footerHtml += '&nbsp;&yen;&nbsp;' + base.setNumberDecimals(gapPrice);
		}else{
			footerHtml += '&nbsp;&yen;&nbsp;' + price;
		}
		$('#vip-payType').show();
		userScoreSum = userScoreMoney;
	}
	if(type == 1){
		$('#vip-payType').show();
	}

	if($('#vip_score_sum').prev().hasClass('current')){
		//有使用积分,支付金额就是全价-积分抵扣金额
		vip.useMyScore = userScoreSum*100;
		if(gapPrice < 0){
			//积分足够
			vip.payMoney = 0;
		}else{
			vip.payMoney = base.setNumberDecimals(gapPrice);
		}
	}else{
		vip.useMyScore = 0;
		vip.payMoney = price;
	}
	$('#userScoreSum').html(userScoreSum);
	$('#userScoreSumso').html(parseInt(userScoreSum*100));
	$('#footer a').html(footerHtml);
}

/**
 * 选择积分支付
 * @method vip.selectScoreBox
 */
vip.selectScoreBox = function(){
	if($('#vip_score_sum').prev().hasClass('current')){
		//已选中,取消选中
		$('#vip_score_sum').prev().removeClass('current');
		vip.useScore(1);
	}else{
		$('#vip_score_sum').prev().addClass('current');
		vip.useScore(2);
	}
}

/**
 * 确认支付，购买VIP
 * @method vip.submitPay
 */
vip.submitPay = function(){
   	if(!base.checkBtnLock()){    //防止重复提交
		return false;
    }
    $('#footer a').html('正在支付...').addClass('unClickBtn');

	var long_time = "";
	var money = "";
	var level = $('#getVipLevel').val();
	$("#vipOpenTime a").each(function(){
		if($(this).hasClass('current')){
			long_time = $(this).data('month');
			money = $(this).data('price');
		}
	});
	var url = api_host + '/Api/Users/create_member';
	var openid = user.userBase.bingo_openid;
	if (openid == undefined || openid == null || openid.length == 0){
		return false;
	}
	var data = {
		bingo_access_token: openid
		,bingo_openid: openid
		,level_id: level
		,long_time: long_time
		,scroe: vip.useMyScore        //使用积分
		,money: vip.payMoney
	};
	$.ajax({type: 'post', url: url, data: data, dataType: 'json',success: function(result){
		if(result.status != 1){
			tipsBox.createAlertBox(result.data);
		    $('#footer a').html('确认支付').removeClass('unClickBtn');
		}
		var hrefUrl = "";
		if(vip.payMoney > 0){
			//微信支付跳转
			if (window.location.host  == "test.bingofresh.com"){//测试服务器
				hrefUrl = "http://pay.bingofresh.com/wxpay_new/Member_pay.php?out_trade_no=" + result.data.out_trade_no + "&is_test=1&open_id=" + openid;
			}else{
				hrefUrl = "http://pay.bingofresh.com/wxpay_new/Member_pay.php?out_trade_no=" + result.data.out_trade_no + "&open_id=" + openid;
			}
		}else{
			user.islogin = 0;
			home.productList = null;
			hrefUrl = "#/home";
			common.delCookie('friend_first_come');
		}
		window.location.href = hrefUrl;
	}});
}

/**
 * 跳转到会员页面
 * @method vip.goToVip
 */
vip.goToVip = function(){
	tipsBox.hideTipsBox();
	window.location.href = "#/vip/0";
}

/**
 * 点击显示会员特权项
 * @method vip.showVipItem
 * @param {Number} type 按钮类型
 */
vip.showVipItem = function(type){
	var html = "";
	switch(type){
		case 1:
			//满28元免运费，未满只需2元
			html += '<h1 class="tipsBoxImgH1"><img src="./ui/images/vip/btn_item_i1.png"/></h1>';
			html += '<h2>缤果免运费门槛是多少？</h2>';
			html += '<p>珠海、中山的普通用户，单笔订单金额满49元，可免4元运费。若单笔订单不满49元，则需支付4元运费。<br>成为缤果会员，单笔订单只需满28元，即可免除运费；若单笔订单不满28元，需支付2元运费。</p>';
			html += '<h2>免运费如何计算</h2>';
			html += '<p>将商品添加到购物车，若购买的商品金额满足免运费的条件，则在提交订单时，将不会计算运费。</p>';
			html += '<h2>什么商品可参与免运费？</h2>';
			html += '<p>缤果商城中，所有正价、特价、加价购以及团购商品，只要满足免运费门槛，即可免收运费；<br>缤果订悦水果不收取任何运费，因此不参与会员下单满28元免运费。</p>';
			break;
		case 2:
			//消费满100元返现余额5元
			html += '<h1 class="tipsBoxImgH1"><img src="./ui/images/vip/btn_item_i2.png"/></h1>';
			html += '<h2>什么是消费返现？</h2>';
			html += '<p>消费返现是指：缤果会员用户在缤果商城，当月下单购买缤果正价商品（包括水果、礼盒、零食、牛奶以及食材）、团购商品、加价购（换购）商品，以及特价商品时，每累计消费满100元，可获得5元余额返现；<br>返现的金额直接发放到用户账户余额，用户可通过【个人中心—我的充值 】查看账户余额。</p>';
			html += '<h2>如何得知我的消费返现进度？</h2>';
			html += '<p>消费返现从成为缤果会员用户开始，每次下单并完成了该笔订单后，订单所消费的金额将累积到消费返现进度条中；<br>消费进度条可在【个人菜单】或【会员特权】页面查看到，消费进度每个自然月月底清零，请及时留意。</p>';
			html += '<h2>消费返现金额什么时候到账？</h2>';
			html += '<p>消费返现按订单下单时间为准，订单完成后可获得返现金额；<br>值得注意的是，若该笔订单刚好跨月配送（即本月下单，下月配送），则返现进度会累积到本月进度条，下月完成订单时将无法获得累积进度。</p>';
			html += '<h2>消费返现的上限是多少？</h2>';
			html += '<p>每月第一天凌晨0点开始，到每月月底最后一天晚上12点结束，缤果会员用户消费的金额，每累计满100元即可返现5元余额，但每个自然月最多可累计返现40元，即消费满800元之后，再消费将不会获得任何返现。</p>';
			html += '<h2>水果订悦是否可累积返现？</h2>';
			html += '<p>水果订悦业务目前暂时无法累积返现，因此给你带来不便请谅解，谢谢你的支持！</p>';
			break;
		case 3:
			//可购买缤果会员专属商品/团购
			html += '<h1 class="tipsBoxImgH1"><img src="./ui/images/vip/btn_item_i3.png"/></h1>';
			html += '<h2>什么是会员专属商品？</h2>';
			html += '<p>会员专属商品是宾哥为广大缤果会员准备的超级福利，缤果会员将以超低价格享受部分正价商品（包括团购）。<br>专属商品/团购只有中山、珠海已开通缤果会员的用户才可以购买，其他地区或非缤果会员用户无法购买。</p>';
			html += '<h2>会员专属商品长期有效吗？</h2>';
			html += '<p>专属商品长期有效，商品库存会每日更新，当天没有购买到的用户，第二天请及时留意商品库存更新；<br>专属商品/团购内容也会不定期更换，请及时留意哦！</p>';
			break;
		case 4:
			//承诺3小时内上门退换货
			html += '<h1 class="tipsBoxImgH1"><img src="./ui/images/vip/btn_item_i4.png"/></h1>';
			html += '<h2>会员可享受3小时内上门退换吗？</h2>';
			html += '<p>成为缤果会员后若有商品需退换货，店长将会优先安排你的退换货订单，并承诺3小时内将上门取货完成退换处理；</p>';
			html += '<h2>如何申请退换货？</h2>';
			html += '<p>1.完成订单后72小时内，若商品出现任何问题，缤果将无条件退换货，用户只需在【个人中心-我的订单-已收货订单】页面点击【退货/换货】，即可根据需要退换商品；<br>2.超过72小时以上的订单，将无法申请退换货操作，敬请留意；<br>3.退换货时可选择【原路退回】或【鲜赔理】退款，选择【原路退回】的用户，缤果将在3小时内上门退换货；选择【鲜赔理】的用户，缤果会先将退/换货的金额发放到你的账户余额，再由送货员3小时内上门处理问题商品。</p>';
			break;
		case 5:
			//订单配送超时补偿代金券
			html += '<h1 class="tipsBoxImgH1"><img src="./ui/images/vip/btn_item_i5.png"/></h1>';
			html += '<h2>什么是超时送券？</h2>';
			html += '<p>缤果会员用户下单时，选择收货时间，若缤果送货员将订单送达用户手中时，超出了用户预定的时间，则系统将自动补偿会员用户一张【超时道歉券】，用以对用户订单配送超时作出补偿和道歉。<br>【超时道歉券】面额为5元，在缤果商城下单超过40元可使用，点击【个人中心—我的优惠券】可查看当前所拥有的代金券。</p>';
			html += '<h2>如何使用代金券？</h2>';
			html += '<p>1.用户下单时，将商品加入购物车并点击去结算进入购物中心，填写收货信息后，可选择使用代金券；<br>2.若购买的商品价格未达到代金券使用门槛，则无法使用相应的代金券，敬请留意。</p>';
			break;
		case 6:
			//更多会员特权敬请期待
			html += '<h1 class="tipsBoxImgH1"><img src="./ui/images/vip/btn_item_i6.png"/></h1>';
			html += '<p>未来将开放更多缤果会员特权<br>若你有什么想法或建议，欢迎通过【个人中心-宾哥信箱】给我们留言！<br>感谢你的支持！</p>';
			break;
		default:
	}
	common.tipsBoxScroll(html);
}

/**
 * 个人菜单页面获取会员返现进度，并处理渲染数据
 * @method vip.getVipCashBack
 */
vip.getVipCashBack = function(){
	var url = api_host + '/Api/Users/back_money_process';
	var openid = user.userBase.bingo_openid;
	if(openid == undefined || openid == null || openid.length == 0){
		return false;
	}
	var data = {
		uid: user.userBase.id
	}
	$.ajax({type: 'POST',dataType: 'json',data: data,url: url, success: function(result){
		if(result.status != 1){
			tipsBox.createAlertBox(result.data);
			return false;
		}
		user.userBase.vipBack = result.data;
		$('#vip-cash-back-loading').hide();
		$('#ac-LoCashBackProgressDiv').removeClass('vip-cashBack-Animation');
		$('#vip-cash-back').show();
		var html = "";
		if(result.data.shengyu == 0){
			$('#ac-cashBackProgressDiv').addClass('progress100').css('width','100%');
			html = '您已获取本月全部返现额度!';
		}else{
			$('#ac-cashBackProgressDiv').css('width', result.data.benci + '%');
			var benci = base.setNumberDecimals(result.data.benci);
			var bencishenyu = base.setNumberDecimals(100 - benci);
			html = '当前返现消费进度为' + result.data.benci + '元<br>还差<span style="color: #fff606;">' + bencishenyu + '</span>元即可获取5元余额返现';
		}
		$('#vip-cash-back p').html(html);
	}});
}
/**
 * 优惠券
 * 功能: 优惠券列表, 优惠券详细情, 优惠券转送
 */
var voucher = {};

/**
 * 显示用户的优是券
 * @method voucher.showUserVoucher
 */
voucher.showUserVoucher = function() {
    var html = template('voucher/voucher', {});
    $("#app_content").html(html);
    if(notice.returnStatus == 1) {
        $('#notice-return').val(1);
    }
    notice.control('voucher');
    voucher.menu('unused');
    voucher.getVoucherList('unused');
    voucher.getVoucherList('expire');
    common.loaded(0);
}

/**
 * 优惠券菜单
 * @method voucher.menu
 * @param {String} type 优惠券的类型
 */
voucher.menu = function(type) { //菜单
    $("html,body").scrollTop(0);
    $('#header-common-main span').removeClass('ft-color');
    $('#header-common-main span').removeClass('bd-color');
    $('.voucher-list-main').hide();

    $('#'+type).addClass('ft-color');
    $('#'+type).addClass('bd-color');
    $('#voucher-'+type).show();
}

/**
 * 获得优惠券列表
 * @method voucher.getVoucherList
 * @param {String} type 优惠券类型
 */
voucher.getVoucherList = function(type) { //优惠券
    var openid = user.userBase.bingo_openid;
    var url = api_host+"/Api/Voucher/voucher_list";
    var data = { "bingo_access_token": openid, "bingo_openid": openid, "type": type, "buycar": "" };
    $.ajax({type:'post',url: url, data: data, dataType: 'json', success: function(data) {
        switch (type) {
            case 'unused': //未过期
                if(data.data != '') {
                    user.userBase.none_all_count = user.userBase.none_all_count - user.userBase.voucher_count;
                    user.userBase.voucher_count = 0;
                    common.renderTpl("#voucher-unused",'voucher/voucher_unused', data);
                } else {
                    common.noFoundResult('你没有未使用代金券哦',"#voucher-unused");
                }
                break;
            case 'expire': //已过期
                if(data.data != '') {
                    common.renderTpl("#voucher-expire",'voucher/voucher_expire', data);
                } else {
                    common.noFoundResult('你没有已过期代金券哦','#voucher-expire');
                }
                break;
        }
    }});
}

/**
 * 查看优惠券详情
 * @method voucher.checkVoucher
 * @param {Number} id 优惠券id
 */
voucher.checkVoucher = function(id) {
    var openid = user.userBase.bingo_openid;
    var url = api_host+"/Api/Voucher/voucher_view";
    var data = { "bingo_access_token": openid, "id": id };
    $.ajax({type:'post', url: url, data: data, dataType: 'json', success:function(data){

        common.renderTpl("#app_content",'voucher/voucher_view', data.data);

        voucher.createVoucherStyle();
        common.loaded(0);
        if(data.data['give_type'] == 1) {
            $('.voucher-footer').show();
            share_info = {
                "title":"恭喜你，获得一张"+data.data['money']+"元优惠券",
                "img_url":data.data['img'],
                "content":user.userBase.nickname+"送你一张价值"+data.data['money']+"元的优惠券，可在缤果商城使用",
                "url":'http://'+window.location.host+'/go.php?go=vouchershare&open_id='+openid+'&id='+id
            };
        }
    }});
}

/**
 * 查看优惠券信息
 * @method voucher.readMessage
 * @param {Number} id 优惠券id
 * @param {Number} status 状态，0:未读，1:已读
 */
voucher.readMessage = function(id,status) {
    if(status == 0) {
        user.userBase.voucher_count--;
        user.userBase.none_all_count--;
    }
    window.location.href = '#/voucherview/'+id;
    return false;
}

/**
 * 分享优惠券
 * @method voucher.shareVoucher
 * @param {String} admin_openid 分享者的openid
 * @param {Number} vid 优是券id
 */
voucher.shareVoucher = function(admin_openid, vid) {
    var openid = user.userBase.bingo_openid;
    var url = api_host+"/Api/Voucher/give_info";
    var data = { "bingo_access_token": openid, "weixin_openid": admin_openid, "voucher_id": vid};
    $.ajax({type:'post',url: url,data: data, dataType: 'json',success:function(data){
        common.renderTpl("#app_content",'voucher/voucher_share', data.data);

        voucher.createVoucherStyle();
        $('.account-mune-btn').hide();
        if(data.data.give_status == "0") {
            if(data.data.uid == user.userBase.id) {
                data.data.give_status = -1;
            }
        }
        bingo.setBoxMinHeight('#voucherview-wrap');
        var html = '<a href="javascript:void(0);" class="default-btn prize-btn deny-btn"  onclick="voucher.givingVoucher(\''+data.data.give_status+'\',\''+data.data.admin_openid+'\',\''+user.userBase.id+'\',\''+vid+'\')">立即领取</a>';
        $('#voucher-share-btn').html(html);
        if(data.data.give_status != 1) {
            $('#voucher-share-btn a').css('backgroundColor','#999');
        }
        common.loaded(0);
        data.data['admin_nickname'] = data.data['admin_nickname'] != '' ? data.data['admin_nickname'] : user.userBase.nickname;
        share_info = {
            "title":"恭喜你，获得一张"+data.data['money']+"元优惠券",
            "img_url":data.data['img'],
            "content":data.data['admin_nickname']+"送你一张价值"+data.data['money']+"元的优惠券，可在缤果商城使用",
            "url":'http://'+window.location.host+'/go.php?go=vouchershare&open_id='+data.data.admin_openid+'&id='+vid
        };
    }});
}

/**
 * 生成优惠优惠券样式
 * @method voucher.createVoucherStyle
 */
voucher.createVoucherStyle = function() {
    var width = $(window).width();
    var save = $('.voucher-save span').html();
    $('.voucher-save').css('fontSize',width * 0.07);
    $('.voucher-save span').css('fontSize',width * 0.12);
    $('.voucher-save span').html(parseInt(save));
}


/**
 * 领取优惠券
 * @method voucher.givingVoucher
 * @param {Number} status 领取的状态: 1,可以领取,0:领取完了, -1,已经领取过了
 * @param {String} host 优惠券主人openid
 * @param {Number} uid 用户id
 * @param {Number} vid 优惠惠id
 * @returns {boolean}
 */
voucher.givingVoucher = function(status,host,uid,vid) {
    if(status == 1) {
        var openid = user.userBase.bingo_openid;
        var url = api_host+"/Api/Voucher/voucher_give";
        var data = { "bingo_access_token" : openid,"admin_openid":host,"user_id":uid,"voucher_id" : vid};
        $.ajax({type:'post',url:url,data:data,dataType: 'json', async:false, success:function(result){
            if(result.status == 1) {
                if(user.userBase.user_type == 1) {
                    tipsBox.createConfirmBox('领取成功，去我的优惠券里查看？','voucher.goVoucher',1,'确定');
                } else {
                    tipsBox.createConfirmBox('关注缤果水果才能查看我的优惠券里查哦,现在去关注?','voucher.goVoucher',0,'确定');
                }
                $('.cart-box-wrap').html('<a href="javascript:void(0);"  class="cart-btn" onclick="voucher.givingVoucher(-1)">领取</a>');
                $('.cart-box-wrap a').css('backgroundColor','#999');
                common.no_juml_url = 0;
            } else {
                tipsBox.createAlertBox(result.data);
            }
        }});
    } else if(status == -1) {
        tipsBox.createAlertBox('你已经领取过了，这张优惠券只能领取一次喔');
    } else {
        tipsBox.createAlertBox('优惠券已经给领取了，你来晚了哦~');
    }
}


/**
 * 前往优惠券列表
 * @method voucher.goVoucher
 * @param {Number} status 状态: 0,没关注 1: 已关注
 */
voucher.goVoucher = function(status) {
    tipsBox.hideTipsBox();
    if(status == 1) {
        window.location.href='http://'+window.location.host+'/go.php?go=voucher';
    } else {
        window.location.href = "http://mp.weixin.qq.com/s?__biz=MzA4NzAwMzAwOQ==&mid=200863069&idx=1&sn=9d5d2b8884ab97d90c8ab6532df958db#rd";
    }
}





